package com.shensi.appCollect.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson.JSON;
import com.shensi.api.admin.client.station.ClassSettlementClient;
import com.shensi.api.admin.domian.integral.dto.CustomerPointsRecord;
import com.shensi.api.admin.domian.station.ClassSettlement;
import com.shensi.appCollect.pojo.AppUserInfo;
import com.shensi.api.order.domian.station.PayOrder;
import com.shensi.appCollect.controller.QuJiaPayController;
import com.shensi.appCollect.dao.*;
import com.shensi.appCollect.enums.PayTypeEnum;
import com.shensi.appCollect.enums.PrintEnum;
import com.shensi.appCollect.enums.ReceiptType;
import com.shensi.appCollect.param.response.YunhuaPayRes;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.pojo.dto.BroadcastCancelOrderDTO;
import com.shensi.appCollect.rocketmq.SettleInfoProducer;
import com.shensi.appCollect.service.*;
import com.shensi.appCollect.utils.*;
import com.shensi.appCollect.utils.exception.CustomException;
import com.shensi.appCollect.utils.exception.EndingException;
import com.shensi.appCollect.utils.redis.RedisCacheUtil;
import com.shensi.appCollect.utils.weixinapp.WxPushUtil;
import com.shensi.appCollect.utils.weixinapp.WxTemplateData;
import com.shensi.appCollect.utils.weixinapp.WxTemplateMsg;
import com.shensi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Service("gzhNewsTemplateService")
public class GzhNewsTemplateServiceImpl implements GzhNewsTemplateService {

    private static Logger logger = (Logger) LoggerFactory.getLogger(QuJiaPayController.class);

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;

    @Resource
    private WxPushUtil wxPushUtil;

    @Value("${qujia.domainName}")
    private String domainName;

    @Value("${qujia.bgBaseUrl}")
    private String bgBaseUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private GzhNewsTemplateMapper gzhNewsTemplateMapper;

    @Resource
    private PosMachineMapper posMachineMapper;

    @Resource
    private EnterpriseMapper enterpriseMapper;

    @Resource
    private SysUserService sysUserService;


    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private PayOrderService payOrderService;

    @Resource
    private SettleInfoProducer settleInfoProducer;

    @Resource
    private PayWayMapper payWayMapper;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private SettleInfoRecordMapper settleInfoRecordMapper;

    @Resource
    private AppUserInfoService appUserInfoService;

    @Resource
    private CustomerPointsRecordService customerPointsRecordService;

    @Resource
    private DeviceService deviceService;

    @Resource
    private PresentAmountRecordMapper presentAmountRecordMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IReceiptSectionService receiptSectionService;
    @Autowired
    private PayOrderHistoryMapper payOrderHistoryMapper;
    @Autowired
    private PosMachineServiceImpl posMachineService;
    @Autowired
    private PhysicalCardBalanceService physicalCardBalanceService;




    //获取公众号消息模板
    @Override
    @Cacheable(value = {"GzhNewsTemplateServiceImpl_getGzhNewsTemplate"},
            key = "'s_' + #root.args[0].getStationId() + 't_' + #root.args[0].getTemplateType()",
            cacheManager = "cacheManager1H",
            condition = "#root.args[0].getStationId()  != null && #root.args[0].getTemplateType() != null"
    )
    public GzhNewsTemplate getGzhNewsTemplate(GzhNewsTemplate gzhNewsTemplate) {
        GzhNewsTemplate gzh = gzhNewsTemplateMapper.getGzhNewsTemplate(gzhNewsTemplate);
        log.info("gzh: " + gzh);

        if (gzh != null) {
            return gzh;
        }

        Enterprise enterprise = enterpriseMapper.selectEnterpriseInfo(gzhNewsTemplate.getStationId());
        GzhNewsTemplate gzh2 = new GzhNewsTemplate();
        if ("1".equals(enterprise.getIsPlatformFlag())) {
            String templateType = gzhNewsTemplate.getTemplateType();
            gzh2.setTemplateType(templateType);
            if ("1".equals(templateType)) {
                gzh2.setTemplateId("yIywEX4O1iAlQBce1wOAPj2D97Vk63YuObYcNIvN9gM");
            } else if ("2".equals(templateType)) {
                gzh2.setTemplateId("xU9q-zvBPI-snOhJofGR2IWX-1iu3bHzWe2vcOX1Co8");
            } else if ("3".equals(templateType)) {
                gzh2.setTemplateId("C85CBwp5xmInYkjSJh46B4tUhhIwGvNfdH-HAesDHxA");
            } else if ("5".equals(templateType)) {
                gzh2.setTemplateId("QS5rlCnEFYxLJryCJxlxRqZ8k3nw2WOf3FoHAoSDFw8");
            }
        }
        return gzh2;
    }

    /**
     * 微信消费通知
     */

    @Async
    @Override
    public void pushConsumeToUser(AppUserInfo appUserInfo, PayOrder payOrder, Integer integral) {

        String gzhAppId = "";
        String gzhAppSecret = "";

        if (integral == null) {
            integral = 0;
        }


        try {
            if (appUserInfo.getStationId() == null) { // 油企存油站，我服气
                throw new EndingException(">pushConsumeToUser" + "-" + appUserInfo.getMobilePhone() + "--" + "油企为空");
            }

            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(appUserInfo.getStationId());
            gzhAppId = enterprise.getGzhAppId();
            gzhAppSecret = enterprise.getGzhAppSecret();

            if (StringUtils.isBlank(enterprise.getGzhAppId()) || StringUtils.isBlank(enterprise.getGzhAppSecret())) {
                logger.info(">pushConsumeToUser" + "-" + appUserInfo.getMobilePhone() + "--" + "未配置公众号信息");
                return;
            }

            if (StringUtils.isBlank(appUserInfo.getBlogOpenid())) {
                logger.info(">pushConsumeToUser" + "-" + appUserInfo.getMobilePhone() + "--" + "没有openid");
                return;
            }

            GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
            gzhNewsTemplate.setStationId(appUserInfo.getStationId());
            gzhNewsTemplate.setTemplateType("4");
            GzhNewsTemplate gzhNewsTemplateInfo = getGzhNewsTemplate(gzhNewsTemplate);

            if (gzhNewsTemplateInfo == null || gzhNewsTemplateInfo.getTemplateId() == null) {
                logger.info(">pushConsumeToUser" + "-" + appUserInfo.getMobilePhone() + "--" + "尚未配置模板id");
                return;
            }

            WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
            wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
            wxTemplateMsg.setTouser(appUserInfo.getBlogOpenid());

            String url = "https://" + domainName + "/" + appUserInfo.getStationId() + "/my";
            wxTemplateMsg.setUrl(url);

            Map<String, WxTemplateData> templateDataMap = new HashMap<>();

            String payTyp = payOrder.getPayType();
            StringBuilder payTypeName = new StringBuilder("");

            switch (payTyp) {
                case "wx":
                    payTypeName.append("微信支付");
                    break;
                case "zfb":
                    payTypeName.append("支付宝支付");
                    break;
                case "dzk":
                    payTypeName.append("电子卡支付");
                    break;
                case "xj":
                    payTypeName.append("现金支付");
                    break;
                case "hyk":
                    payTypeName.append("实体卡");
                    break;
                case "yl":
                    payTypeName.append("银联支付");
                    break;
                default:
                    //语句
            }
            StringBuilder remarkString = new StringBuilder("");

            // 电子卡余额
            if (payTyp == "dzk") {
                Oil oil = enterpriseService.selectOilByOilName(payOrder.getOilName());

//                CustomerElectronicCard electronicCardInfoByPhone
//                        = electronicMembershipCardService.getElectronicCardInfoByPhone(CustomerElectronicCard.builder()
//                        .stationId(appUserInfo.getStationId())
//                        .cardOilsType(oil.getCardType())
//                        .mobilePhone(appUserInfo.getMobilePhone()).build());
                Station station = new Station();
                station.setEnterprise(enterprise);
                station.setStationId(payOrder.getStationId());
                CustomerElectronicCard electronicCard = electronicMembershipCardService.getCustomerElectronicCard(appUserInfo, oil.getCardType(), station);
                BigDecimal cardAmt = electronicCard == null ? BigDecimal.ZERO : electronicCard.getTotalAmt();
                String cardType = null;

                switch (oil.getCardType()) {
                    case "1":
                        cardType = "汽油卡";
                        break;
                    case "2":
                        cardType = "柴油卡";
                        break;
                    case "3":
                        cardType = "LNG卡";
                    case "4":
                        cardType = "CNG卡";
                }
                remarkString.append("\n").append(cardType + "余额为" + cardAmt.toString() + "元~");
            }

            // 支付成功的消息推送
            Station station = enterpriseService.selectStationById(payOrder.getStationId());
            if (station != null && StringUtils.isNotEmpty(station.getStationPayPush())) {
                remarkString.append("\n\n");
                remarkString.append(station.getStationPayPush());
            } else {
                remarkString.append("\n我站加油更优惠，点击此消息进入会员中心~");
            }


            templateDataMap.put("first", WxTemplateData.builder().value("您在" + payOrder.getStationName() + "的最新交易信息如下").build());
            templateDataMap.put("time", WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
            templateDataMap.put("org", WxTemplateData.builder().value(payOrder.getStationName()).build());
            templateDataMap.put("type", WxTemplateData.builder().value(payTypeName.toString()).build());
            templateDataMap.put("money", WxTemplateData.builder().value("实付" + payOrder.getAmt() + "元，应付" + payOrder.getReceivableAmt() + "元").build());
            templateDataMap.put("point", WxTemplateData.builder().value(integral + "积分，可用" + (appUserInfo.getIntegral() == null ? 0 : appUserInfo.getIntegral()) + "积分").build());
            templateDataMap.put("remark", WxTemplateData.builder().value(remarkString.toString()).build());


            wxTemplateMsg.setData(templateDataMap);
            wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);
            logger.info(">pushConsumeToUser" + "-" + appUserInfo.getMobilePhone() + "--" + "消息推送完成");

        } catch (EndingException e) {
            logger.info(e.getMessage());

        } catch (Exception e) {
            logger.error(">pushConsumeToUser", e);
        }
    }

    @Async
    @Override
    public void elecOrderPush(CustomerCardUseRecord customerCardUseRecord) {
        log.info("customerCardUseRecord======【{}】", customerCardUseRecord);
        //充值金额
        BigDecimal amt = customerCardUseRecord.getAmt();

        //赠送金额
        BigDecimal presentAmt = customerCardUseRecord.getPresentAmt();

        //用户名
        String customerName = customerCardUseRecord.getCustomerName();

        String mobilePhone = customerCardUseRecord.getMobilePhone();

        //电子卡充值方式
        String payType = customerCardUseRecord.getPayType();
        log.info("payType{}", payType);
        String curPaytype = "";
        if (StringUtils.isNotBlank(payType)) {
            switch (payType) {
                case "WECHAT":
                    curPaytype = "微信支付";
                    break;
                //目前只有电子卡充值只有微信支付
            }
        } else {
            curPaytype = "微信支付";
        }
        log.info("curPaytype{}", curPaytype);
        //
        Date payTime = customerCardUseRecord.getPayTime();

        String orderNo = customerCardUseRecord.getOrderNo();

        //
        Date createTime = customerCardUseRecord.getCreateTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        StationDeviceManager stationDeviceManager = new StationDeviceManager();
        stationDeviceManager.setStationId(customerCardUseRecord.getStationId());
        stationDeviceManager.setDeviceType("3");
        List<StationDeviceManager> stationDeviceManagers = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
        if (stationDeviceManagers == null || stationDeviceManagers.size() <= 0) {
            return;
        }


        StationDeviceManager stationDeviceManagerRes = stationDeviceManagers.get(0);


        HashMap<String, String> audioMap = new HashMap<>();
        audioMap.put("手机尾号", customerCardUseRecord.getMobilePhone().substring(7, 11));
        audioMap.put("充值金额", customerCardUseRecord.getAmt().toString() + "元");

        PresentAmountRecord presentAmountRecord = new PresentAmountRecord();
        presentAmountRecord.setOrderNo(customerCardUseRecord.getOrderNo());
        List<PresentAmountRecord> presentAmountRecords = presentAmountRecordMapper.query(presentAmountRecord);

        BigDecimal dzkPresentAmt = CollectionUtils.isEmpty(presentAmountRecords) ? BigDecimal.ZERO : presentAmountRecords.get(0).getPresentAmount();

        audioMap.put("赠送金额", dzkPresentAmt.toString() + "元");
        List<String> rechargeAudioList = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        try {
            String rechargeAudio = stationDeviceManagerRes.getAudio();


            List<String> audioList = Arrays.asList(rechargeAudio.split(";"));
            String rechargeAudioString = audioList.get(2);
            log.info("充值订单语音播报rechargeAudio{}", rechargeAudioString);
            rechargeAudioList = Arrays.asList(rechargeAudioString.split(","));

            sb.append("<audio>");
            for (String audioContent : rechargeAudioList) {
                sb.append(audioContent + audioMap.get(audioContent));
            }
            sb.append("</audio>");
        } catch (Exception e) {
            sb = new StringBuffer("<audio>手机尾号").append(customerCardUseRecord.getMobilePhone().substring(7, 11))
                    .append("充值金额").append(customerCardUseRecord.getAmt()).append("元").append("赠送金额").append(dzkPresentAmt).append("元</audio>");

        }
        log.info("播报语音：{}", sb);

        CustomerPointsRecord customerPointsRecordQuery = new CustomerPointsRecord();
        customerPointsRecordQuery.setOrderNo(customerCardUseRecord.getOrderNo());
        CustomerPointsRecord customerPointsRecordRes = customerPointsRecordService.getOne(customerPointsRecordQuery);
        String integral = Objects.nonNull(customerPointsRecordRes) ? customerPointsRecordRes.getIntegral().toString() : "0";
        String deviceFactory = stationDeviceManagerRes.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);

        StringBuffer stringBuffer = new StringBuffer();

        Station station = stationMapper.selectStationById(customerCardUseRecord.getStationId());
        String stationName = station.getStationName();

        switch (printEnum) {
            case YILIANYUNK4:
                stringBuffer.append("<FS2><center>" + stationName + "</center></FS2>\r\n");
                stringBuffer.append("<center>【充值】</center>\r\n");
                break;
            case YILIANYUN:
                stringBuffer.append("<FS2><center>" + stationName + "</center></FS2>\r\n");
                stringBuffer.append("<center>【充值】</center>\r\n");
                break;
            case FEIE:
                stringBuffer.append("<BOLD><C><B>" + stationName + "</B></C></BOLD>\r\n");
                stringBuffer.append("<C>【充值】</C>\r\n");
                break;
        }

        StringBuffer content = stringBuffer.append("会员名称：").append(customerName)
                .append("\r\n手机号：").append(DesensitizedUtil.mobilePhone(mobilePhone))
//                .append ("\r\n充值金额：").append(amt).append("元")
                .append("\r\n订单编号：").append(orderNo)
                .append("\r\n支付方式：").append(curPaytype).append("\r\n");


        switch (printEnum) {
            case YILIANYUNK4:
                content.append("充值金额：<FS>").append(customerCardUseRecord.getAmt()).append("元</FS>\r\n");
                content.append("赠送金额：<FS>").append(customerCardUseRecord.getPresentAmt()).append("元").append("</FS>\r\n");
                content.append("获得积分：<FS>").append(customerCardUseRecord.getIntegral()).append("</FS>\r\n");

                break;
            case YILIANYUN:
                content.append("充值金额：<FS>").append(customerCardUseRecord.getAmt()).append("元</FS>\r\n");
                content.append("赠送金额：<FS>").append(customerCardUseRecord.getPresentAmt()).append("元").append("</FS>\r\n");
                content.append("获得积分：<FS>").append(customerCardUseRecord.getIntegral()).append("</FS>\r\n");

                break;
            case FEIE:
                content.append("<BOLD>充值金额：").append(customerCardUseRecord.getAmt()).append("元</BOLD>\r\n");
                content.append("<BOLD>赠送金额：").append(customerCardUseRecord.getPresentAmt()).append("元").append("</BOLD>\r\n");
                content.append("<BOLD>获得积分：").append(customerCardUseRecord.getIntegral()).append("</BOLD>\r\n");
                break;
        }


        content.append("\r\n充值时间：").append(sdf.format(createTime))
                .append("\r\n--------------------------------")
                .append("\r\n打印时间：").append(DateUtil.now())
                .append("\r\n")
                .append("谢谢惠顾！欢迎下次再来~")
                .append("\r\n")
                .append("\r\n")
                .append("\r\n");


        switch (printEnum) {
            case YILIANYUNK4:
                String ylyContentK4 = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                Integer isPrintK4 = stationDeviceManagerRes.getIsPrint();
                StringBuffer printContentK4;
                StringBuffer sbK4 = new StringBuffer();
                for (String s : rechargeAudioList) {
                    if ("充值金额".equals(s)) {
                        sbK4.append("<VN>6</VN>").append("<VD>").append(amt).append("</VD>").append("<VN>0</VN>");
                    }
                    if ("手机尾号".equals(s)) {
                        if (StringUtils.isNotBlank(customerCardUseRecord.getMobilePhone()) && Validator.isMobile(customerCardUseRecord.getMobilePhone())) {
                            String mobilePhoneK4 = customerCardUseRecord.getMobilePhone().substring(7, 11);
                            log.info("mobilePhone{}", mobilePhoneK4);
                            char[] charsK4 = mobilePhoneK4.toCharArray();
                            log.info("charsK4{}", charsK4);
                            sbK4.append("<VN>").append(1).append("</VN>");
                            for (char aChar : charsK4) {
                                sbK4.append("<VD>").append(aChar).append("</VD>");
                            }
                        }
                    }
                    if ("赠送金额".equals(s)) {
                        sbK4.append("<VN>7</VN>").append("<VD>").append(presentAmt).append("</VD>").append("<VN>0</VN>");
                    }
                }


                if (Objects.nonNull(isPrintK4) && isPrintK4.equals(0)) {
                    printContentK4 = sbK4;
                } else {
                    printContentK4 = sbK4.append(ylyContentK4);
                }

                log.info("K4充值订单打印内容{}", printContentK4);
                log.info("K4小票机信息：{}", stationDeviceManagerRes);

                Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods mK4 = Methods.getInstance();
                Object tokenK4 = redisCacheUtil.getCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId());
                log.info("token:{}", tokenK4);
                if (Objects.nonNull(tokenK4)) {
                    String print = mK4.print(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getDeviceNo(), printContentK4.toString(), random6K4.toString(), tokenK4.toString());
                    log.info("小票机返回值{}", print);
                    JSONObject json = new JSONObject(print);
                    if ("0".equals(json.getString("error"))) {
                        break;
                    }
                }

                //初始化终端信息
                mK4.init(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getClientSecret());
                //获取token
                String refreshTokenK4 = mK4.getFreedomToken();
                log.info("新的token{}", refreshTokenK4);
                //存入redis
                redisCacheUtil.setCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId(), refreshTokenK4, 30, TimeUnit.DAYS);


                String printK4 = mK4.print(stationDeviceManagerRes.getDeviceNo(), printContentK4.toString(), random6K4.toString());
                log.info("小票机返回值2{}", printK4);

                break;
            case YILIANYUN:
                String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                Integer isPrint = stationDeviceManagerRes.getIsPrint();
                StringBuffer printContent;
                if (Objects.nonNull(isPrint) && isPrint.equals(0)) {
                    printContent = sb;
                } else {

                    printContent = sb.append(ylyContent);
                }

                log.info("充值订单打印内容{}", printContent);
                log.info("小票机信息：{}", stationDeviceManagerRes);

                Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods m = Methods.getInstance();
                Object token = redisCacheUtil.getCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId());
                log.info("token:{}", token);
                if (Objects.nonNull(token)) {
                    String print = m.print(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getDeviceNo(), printContent.toString(), random6.toString(), token.toString());
                    log.info("小票机返回值{}", print);
                    JSONObject json = new JSONObject(print);
                    if ("0".equals(json.getString("error"))) {
                        break;
                    }
                }

                //初始化终端信息
                m.init(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getClientSecret());
                //获取token
                String refreshToken = m.getFreedomToken();
                log.info("新的token{}", refreshToken);
                //存入redis
                redisCacheUtil.setCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId(), refreshToken, 30, TimeUnit.DAYS);


                String print = m.print(stationDeviceManagerRes.getDeviceNo(), printContent.toString(), random6.toString());
                log.info("小票机返回值2{}", print);
                break;
            case FEIE:
                FeiEPrinterUtil.printReceipt(stationDeviceManagers.get(0).getDeviceNo(), content.toString());
                break;
            default:
                log.info("没有配置小票机，打印失败");
                break;
        }
    }

    @Override
    @Async
    public void saleOrderPush(SaleActivityOrder activityOrder) {
        log.info("SaleActivityOrder======[{}]", activityOrder);
        StationDeviceManager stationDeviceManager = new StationDeviceManager();
        stationDeviceManager.setStationId(Math.toIntExact(activityOrder.getStationId()));
        stationDeviceManager.setDeviceType("3");
        List<StationDeviceManager> stationDeviceManagers = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
        if (stationDeviceManagers == null || stationDeviceManagers.size() <= 0) {
            return;
        }
        StationDeviceManager deviceManager = stationDeviceManagers.get(0);
        String deviceFactory = deviceManager.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
        StringBuilder sb = new StringBuilder();

        switch (printEnum) {
            case YILIANYUNK4:
                sb.append("<FS2><center>").append(activityOrder.getStationName()).append("</center></FS2>\r\n");
                sb.append("<center>【秒杀订单】</center>\r\n");
                break;
            case YILIANYUN:
                sb.append("<FS2><center>").append(activityOrder.getStationName()).append("</center></FS2>\r\n");
                sb.append("<center>【秒杀订单】</center>\r\n");
                break;
            case FEIE:
                sb.append("<BOLD><C><B>").append(activityOrder.getStationName()).append("</B></C></BOLD>\r\n");
                sb.append("<C>【秒杀订单】</C>\r\n");
                break;
        }
        sb.append("--------------------------------\r\n")
                .append("会员名称：").append(activityOrder.getCustomerName())
                .append("\r\n手机号：").append(DesensitizedUtil.mobilePhone(activityOrder.getMobilePhone()))
                .append("\r\n订单编号：").append(activityOrder.getOrderNo())
                .append("\r\n支付方式：").append(PayTypeEnum.getByType(activityOrder.getPayType(), PayTypeEnum.def).getDes())
                .append("\r\n");
        switch (printEnum) {
            case YILIANYUNK4:
                sb.append("订单金额：<FS>").append(activityOrder.getAmt()).append("元</FS>\r\n");
                break;
            case YILIANYUN:
                sb.append("订单金额：<FS>").append(activityOrder.getAmt()).append("元</FS>\r\n");
                break;
            case FEIE:
                sb.append("<BOLD>订单金额：").append(activityOrder.getAmt()).append("元</BOLD>\n");
                break;
        }
        sb.append("\r\n支付时间：").append(LocalDateTimeUtil.parse(activityOrder.getPayTime()))
                .append("\r\n--------------------------------")
                .append("\r\n打印时间：").append(LocalDateTimeUtil.parse(LocalDateTime.now()))
                .append("\r\n")
                .append("谢谢惠顾！欢迎下次再来~")
                .append("\r\n")
                .append("\r\n")
                .append("\r\n");


        switch (printEnum) {
            case YILIANYUNK4:
                String ylyContentK4 = sb.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                Integer isPrintK4 = deviceManager.getIsPrint();
                StringBuilder printContentK4;
                StringBuilder sbK4 = new StringBuilder();

                if (Objects.nonNull(isPrintK4) && isPrintK4.equals(0)) {
//                    printContentK4 = sbK4;
                    break;
                } else {
                    printContentK4 = sbK4.append(ylyContentK4);
                }

                log.info("K4充值订单打印内容{}", printContentK4);
                log.info("K4小票机信息：{}", deviceManager);

                Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods mK4 = Methods.getInstance();
                Object tokenK4 = redisCacheUtil.getCacheObject("STATION:DEVICE:" + deviceManager.getClientId());
                log.info("token:{}", tokenK4);
                if (Objects.nonNull(tokenK4)) {
                    String print = mK4.print(deviceManager.getClientId(), deviceManager.getDeviceNo(), printContentK4.toString(), random6K4.toString(), tokenK4.toString());
                    log.info("小票机返回值{}", print);
                    JSONObject json = new JSONObject(print);
                    if ("0".equals(json.getString("error"))) {
                        break;
                    }
                }

                //初始化终端信息
                mK4.init(deviceManager.getClientId(), deviceManager.getClientSecret());
                //获取token
                String refreshTokenK4 = mK4.getFreedomToken();
                log.info("新的token{}", refreshTokenK4);
                //存入redis
                redisCacheUtil.setCacheObject("STATION:DEVICE:" + deviceManager.getClientId(), refreshTokenK4, 30, TimeUnit.DAYS);


                String printK4 = mK4.print(deviceManager.getDeviceNo(), printContentK4.toString(), random6K4.toString());
                log.info("小票机返回值2{}", printK4);

                break;
            case YILIANYUN:
                String ylyContent = sb.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                Integer isPrint = deviceManager.getIsPrint();
                StringBuilder printContent;
                StringBuilder audioContent = new StringBuilder();
                if (Objects.nonNull(isPrint) && isPrint.equals(0)) {
//                    printContent = audioContent;
                    break;
                } else {
                    printContent = audioContent.append(ylyContent);
                }

                log.info("充值订单打印内容{}", printContent);
                log.info("小票机信息：{}", deviceManager);

                Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods m = Methods.getInstance();
                Object token = redisCacheUtil.getCacheObject("STATION:DEVICE:" + deviceManager.getClientId());
                log.info("token:{}", token);
                if (Objects.nonNull(token)) {
                    String print = m.print(deviceManager.getClientId(), deviceManager.getDeviceNo(), printContent.toString(), random6.toString(), token.toString());
                    log.info("小票机返回值{}", print);
                    JSONObject json = new JSONObject(print);
                    if ("0".equals(json.getString("error"))) {
                        break;
                    }
                }

                //初始化终端信息
                m.init(deviceManager.getClientId(), deviceManager.getClientSecret());
                //获取token
                String refreshToken = m.getFreedomToken();
                log.info("新的token{}", refreshToken);
                //存入redis
                redisCacheUtil.setCacheObject("STATION:DEVICE:" + deviceManager.getClientId(), refreshToken, 30, TimeUnit.DAYS);


                String print = m.print(deviceManager.getDeviceNo(), printContent.toString(), random6.toString());
                log.info("小票机返回值2{}", print);
                break;
            case FEIE:
                FeiEPrinterUtil.printReceipt(stationDeviceManagers.get(0).getDeviceNo(), sb.toString());
                break;
            default:
                log.info("没有配置小票机，打印失败");
                break;
        }
    }


    @Override
    @Async
    public void pushSettleInfo(PayOrder payOrder, com.alibaba.fastjson.JSONObject obj) {
//        log.info("开始推送订单清分信息。订单{}：", payOrder.toString());
//        //查询mno
//        Integer payWayId = payOrder.getPayWayId();
//        PayWay payWay = payWayMapper.selectPayWayById(Long.valueOf(payWayId));
//
//        Integer stationId = payOrder.getStationId();
//        Station station = stationMapper.selectStationById(stationId);
//        if (com.platform.qujia.utils.StringUtils.isBlank(station.getClearAccount()) || com.platform.qujia.utils.StringUtils.isBlank(station.getClearMerMo())) {
//            return;
//        }
//        String payTime = obj.getString("payTime");
//        String inputFormat = "yyyy-MM-dd'T'HH:mm:ss";
//        String outputFormat = "yyyyMMddHHmmss";
//
//
//        String convertedTimestamp = DateUtil.format(DateUtil.parse(payTime, inputFormat), outputFormat);
//
//
//        //供应商优惠金额
//        BigDecimal merchantDisAmt = new BigDecimal(obj.getString("merchantDisAmt"));
//        //平台优惠金额
//        BigDecimal platformDisAmt = new BigDecimal(obj.getString("platformDisAmt"));
//        //赞助商优惠金额
//        BigDecimal sponsorDisAmt = new BigDecimal(obj.getString("sponsorDisAmt"));
//
//        BigDecimal marketingDisAmt = new BigDecimal(obj.getString("marketingDisAmt"));
//
//        //营销订单号
//        String marketingOrderNo = obj.getString("marketingOrderNo");
//
//        BigDecimal amt = payOrder.getActualAmt();
//        if (amt == null) {
//            // 后台有是否显示服务费需求，amt不是实际支付金额
//            amt = Objects.nonNull(payOrder.getAmt()) ? BigDecimal.valueOf(payOrder.getAmt()) : BigDecimal.ZERO;
//        }
//        SaasOrderBo saasOrderBo = SaasOrderBo.builder()
//                .payOrder(obj.getString("payOrderNo"))
//                .payMerNo(payWay.getMno())
//                .payTime(convertedTimestamp)
//                .orderType("01")
//                .orderAmt(amt)
//                .payAmt(new BigDecimal(obj.getString("payAmt")))
//                .marketingOrder(StringUtils.isNotBlank(marketingOrderNo) ? marketingOrderNo : "")
//                .totalDisAmt(marketingDisAmt)
//                .merchantDisAmt(merchantDisAmt)
//                .platformDisAmt(platformDisAmt)
//                .sponsorDisAmt(sponsorDisAmt)
//                .clearAccount(station.getClearAccount())
//                .clearMerNo(station.getClearMerMo())
//                .optAmt(new BigDecimal("0")).build();
//
//        //发送消息
//
//        settleInfoProducer.sendMessage(saasOrderBo);

        //保存收银台信息
//        insertYunhuaOrderInfo(YunhuaOrderPayInfo.builder()
//                .payOrderNo(obj.getString("payOrderNo"))
//                .marketingDisAmt(obj.getString("marketingDisAmt"))
//                .orderNo(payOrder.getOrderNo())
//                .platformDisAmt(obj.getString("platformDisAmt"))
//                .totalDisAmt(obj.getString("totalDisAmt"))
//                .merchantDisAmt(obj.getString("merchantDisAmt"))
//                .sponsorDisAmt(obj.getString("sponsorDisAmt"))
//                .payAmt(obj.getString("payAmt"))
//                .type(1)
//                .build());

    }

    @Override
    @Async
    public void sendEletricMessage(com.alibaba.fastjson.JSONObject obj, Station station, CustomerCardUseRecord customerCardUseRecordInfo) {
//        Integer stationId = station.getStationId();
//        if (com.platform.qujia.utils.StringUtils.isBlank(station.getClearAccount()) || com.platform.qujia.utils.StringUtils.isBlank(station.getClearMerMo())) {
//            return;
//        }
//
//        PayWay payWay = new PayWay();
//
//        payWay.setStationId(Integer.valueOf(stationId));
//        payWay.setAppType("1");        //支付宝还是微信 目前只有微信能充值电子卡
//        payWay.setUseType("0");             //使用类型
//        //获取该油站的支付类型
//        List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay);
//
//        String payTime = obj.getString("payTime");
//        String inputFormat = "yyyy-MM-dd'T'HH:mm:ss";
//        String outputFormat = "yyyyMMddHHmmss";
//
//
//        String convertedTimestamp = DateUtil.format(DateUtil.parse(payTime, inputFormat), outputFormat);
//        //供应商优惠金额
//        BigDecimal merchantDisAmt = new BigDecimal(obj.getString("merchantDisAmt"));
//        //平台优惠金额
//        BigDecimal platformDisAmt = new BigDecimal(obj.getString("platformDisAmt"));
//        //赞助商优惠金额
//        BigDecimal sponsorDisAmt = new BigDecimal(obj.getString("sponsorDisAmt"));
//        //总优惠
//        BigDecimal marketingDisAmt = new BigDecimal(obj.getString("marketingDisAmt"));
//
//        //营销订单号
//        String marketingOrderNo = obj.getString("marketingOrderNo");
//
//
//        SaasOrderBo saasOrderBo = SaasOrderBo.builder()
//                .payOrder(obj.getString("payOrderNo"))
//                .payMerNo(payWayList.get(0).getMno())
//                .payTime(convertedTimestamp)
//                .orderType("01")
//                .orderAmt(customerCardUseRecordInfo.getAmt())
//                .payAmt(new BigDecimal(obj.getString("payAmt")))
//                .marketingOrder(StringUtils.isNotBlank(marketingOrderNo) ? marketingOrderNo : "")
//                .totalDisAmt(marketingDisAmt)
//                .merchantDisAmt(merchantDisAmt)
//                .platformDisAmt(platformDisAmt)
//                .sponsorDisAmt(sponsorDisAmt)
//                .clearAccount(station.getClearAccount())
//                .clearMerNo(station.getClearMerMo())
//                .optAmt(new BigDecimal("0")).build();
//        settleInfoProducer.sendMessage(saasOrderBo);

        //保存收银台信息
//        insertYunhuaOrderInfo(YunhuaOrderPayInfo.builder()
//                .payOrderNo(obj.getString("payOrderNo"))
//                .marketingDisAmt(obj.getString("marketingDisAmt"))
//                .orderNo(customerCardUseRecordInfo.getOrderNo())
//                .platformDisAmt(obj.getString("platformDisAmt"))
//                .merchantDisAmt(obj.getString("merchantDisAmt"))
//                .sponsorDisAmt(obj.getString("sponsorDisAmt"))
//                .payAmt(obj.getString("payAmt"))
//                .type(0)
//                .build());

    }

    @Override
    @Async
    public void sendPosSettleInfo(YunhuaPayRes yunhuaPayRes, PayWay payWay, PayOrder payOrder) {

//        Integer stationId = payOrder.getStationId();
//        Station station = stationMapper.selectStationById(stationId);
//
//        String payTime = yunhuaPayRes.getPayTime();
//        String inputFormat = "yyyy-MM-dd'T'HH:mm:ss";
//        String outputFormat = "yyyyMMddHHmmss";
//        String convertedTimestamp = DateUtil.format(DateUtil.parse(payTime, inputFormat), outputFormat);
//
//
//        //供应商优惠金额
//        BigDecimal merchantDisAmt = new BigDecimal(yunhuaPayRes.getMerchantDisAmt());
//        //平台优惠金额
//        BigDecimal platformDisAmt = new BigDecimal(yunhuaPayRes.getPlatformDisAmt());
//        //赞助商优惠金额
//        BigDecimal sponsorDisAmt = new BigDecimal(yunhuaPayRes.getSponsorDisAmt());
//        //总优惠金额
//        BigDecimal marketingDisAmt = new BigDecimal(yunhuaPayRes.getMarketingDisAmt());
//
//
//        SaasOrderBo saasOrderBo = SaasOrderBo.builder()
//                .payOrder(yunhuaPayRes.getPayOrderNo())
//                .payMerNo(payWay.getMno())
//                .payTime(convertedTimestamp)
//                .orderType("01")
//                .orderAmt(new BigDecimal(payOrder.getAmt()))
//                .payAmt(new BigDecimal(yunhuaPayRes.getPayAmt()))
//                .marketingOrder(payOrder.getOrderNo())
//                .totalDisAmt(marketingDisAmt)
//                .merchantDisAmt(merchantDisAmt)
//                .platformDisAmt(platformDisAmt)
//                .sponsorDisAmt(sponsorDisAmt)
//                .clearAccount(station.getClearAccount())
//                .clearMerNo(station.getClearMerMo())
//                .optAmt(new BigDecimal("0")).build();
//        settleInfoProducer.sendMessage(saasOrderBo);
    }

    @Override
    @Async
    public void sendStkSettleInfo(PhysicalCardBalance physicalCardBalance, Map<String, Object> res) {
//        String stationId = physicalCardBalance.getStationId();
//        Station station = stationMapper.selectStationById(Integer.valueOf(stationId));
//
//        String payTime = res.get("payTime").toString();
//        String inputFormat = "yyyy-MM-dd'T'HH:mm:ss";
//        String outputFormat = "yyyyMMddHHmmss";
//
//
//        String convertedTimestamp = DateUtil.format(DateUtil.parse(payTime, inputFormat), outputFormat);
//        //供应商优惠金额
//        BigDecimal merchantDisAmt = new BigDecimal(res.get("merchantDisAmt").toString());
//        //平台优惠金额
//        BigDecimal platformDisAmt = new BigDecimal(res.get("platformDisAmt").toString());
//        //赞助商优惠金额
//        BigDecimal sponsorDisAmt = new BigDecimal(res.get("sponsorDisAmt").toString());
//        //总优惠
//        BigDecimal marketingDisAmt = new BigDecimal(res.get("marketingDisAmt").toString());
//
//        //营销订单号
//        //String marketingOrderNo = res.get("marketingOrderNo").toString();
//
//        PayWay payWay = payWayMapper.selectPayWayById(physicalCardBalance.getPayWayId());
//
//        SaasOrderBo saasOrderBo = SaasOrderBo.builder()
//                .payOrder(res.get("payOrderNo").toString())
//                .payMerNo(payWay.getMno())
//                .payTime(convertedTimestamp)
//                .orderType("01")
//                .orderAmt(physicalCardBalance.getAmount())
//                .payAmt(new BigDecimal(res.get("payAmt").toString()))
//                .marketingOrder(physicalCardBalance.getBalanceNo())
//                .totalDisAmt(marketingDisAmt)
//                .merchantDisAmt(merchantDisAmt)
//                .platformDisAmt(platformDisAmt)
//                .sponsorDisAmt(sponsorDisAmt)
//                .clearAccount(station.getClearAccount())
//                .clearMerNo(station.getClearMerMo())
//                .optAmt(new BigDecimal("0")).build();
//        settleInfoProducer.sendMessage(saasOrderBo);
    }

//    @Override
//    public void insertYunhuaOrderInfo(YunhuaOrderPayInfo yunhuaOrderPayInfo) {
//        yunhuaOrderPayInfoMapper.insertYunhuaOrderPayInfo(yunhuaOrderPayInfo);
//    }

    private String getElectronicCardAmt(PayOrder payOrder) {
        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(payOrder.getEnterpriseId());
        String cardUseRangeFlag = enterprise.getCardUseRangeFlag();

        AppUserInfo appUserInfo = appUserInfoService.selectAppUserInfoById(Long.valueOf(payOrder.getConsumerId()));
        log.info("用户信息{}", appUserInfo.toString());
        CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
        customerElectronicCard.setCustomerNo(appUserInfo.getMemberCode());

        if ("1".equals(cardUseRangeFlag)) {
            customerElectronicCard.setStationId(payOrder.getEnterpriseId());
        } else if ("2".equals(cardUseRangeFlag)) {
            customerElectronicCard.setStationId2(payOrder.getStationId());
        }

        String cardOilType = "汽油".equals(payOrder.getOrderType()) ? "1" : "2";
        customerElectronicCard.setCardOilsType(cardOilType);
        log.info("customerElectronicCard:{}", customerElectronicCard);
        CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getElectronicCardInfo(customerElectronicCard);
        log.info("电子卡信息：{}", electronicCardInfo.toString());
        return Objects.nonNull(electronicCardInfo) ? electronicCardInfo.getAmt().toString() : "0";
//        log.info("订单号==={}", payOrder.getOrderNo());
//        CustomerCardUseRecord customerCardUseRecord = electronicMembershipCardService.selectCustomerCardUseRecordByOrderNo(payOrder.getOrderNo());
//        log.info("电子卡消费记录{}", customerCardUseRecord);
//        return Objects.nonNull(customerCardUseRecord) ? customerCardUseRecord.getBalance().toString() : "0";

    }

    @Async
//    @Override
    public void feiePushOld(PayOrder payOrder) { //
        try {
            log.info("payOrder==={}", payOrder);
            String payTyp = payOrder.getPayType();
            String payTypeName = null;
            StationDeviceManager stationDeviceManager = new StationDeviceManager();
            stationDeviceManager.setStationId(payOrder.getStationId());
            stationDeviceManager.setDeviceType("3");
            if (payOrder != null && payOrder.getOilPersonnelId() != null && !"".equals(payOrder.getOilPersonnelId())) {
                stationDeviceManager.setUserIds(payOrder.getOilPersonnelId());
            }
//            if(StringUtils.isNotEmpty(payOrder.getOilGun())){
//                stationDeviceManager.setGunNo(payOrder.getOilGun());
//            }
            List<StationDeviceManager> stationDeviceManagers = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
            //云喇叭
            stationDeviceManager.setDeviceType("4");
            List<StationDeviceManager> stationDeviceManagers1 = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
            stationDeviceManagers.addAll(stationDeviceManagers1);
            //K4小票机
            stationDeviceManager.setDeviceType("5");
            List<StationDeviceManager> stationDeviceManagers2 = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
            stationDeviceManagers.addAll(stationDeviceManagers2);

            //大喇叭机
            stationDeviceManager.setDeviceType("8");
            List<StationDeviceManager> stationDeviceManagers3 = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
            stationDeviceManagers.addAll(stationDeviceManagers3);
            if (stationDeviceManagers == null || stationDeviceManagers.size() <= 0) {
                return;
            }

            switch (payTyp) {
                case "wx":
                    payTypeName = "微信支付";
                    break;
                case "zfb":
                    payTypeName = "支付宝支付";
                    break;
                case "dzk":
                    payTypeName = "电子卡支付";
                    break;
                case "xj":
                    payTypeName = "现金支付";
                    break;
                case "hyk":
                    payTypeName = "实体卡";
                    break;
                case "yl":
                    payTypeName = "银联支付";
                    break;
                case "cdk":
                    payTypeName = "车队卡";
                    break;
                case "pos":
                    payTypeName = "POS机";
                    break;
                case "yhk":
                    payTypeName = "银行卡";
                    break;
                default:
                    break;
            }

            StringBuilder content = new StringBuilder();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            boolean guKeFlag = true;
            boolean shangHuflag = true;
            if ("1".equals(stationDeviceManagers.get(0).getPrintType())) {
                shangHuflag = false;
            }
            if ("2".equals(stationDeviceManagers.get(0).getPrintType())) {
                guKeFlag = false;
            }

            StationDeviceManager stationDeviceManagerRes;
            List<StationDeviceManager> manageWithUser = new ArrayList<>();
            try {
                //筛选绑定了用户的小票机

                if (payOrder != null && payOrder.getOilPersonnelId() != null && !"".equals(payOrder.getOilPersonnelId())) {
                    manageWithUser = stationDeviceManagers.stream().filter(device -> {
//                        if(StringUtils.isNotBlank(device.getUserIds())){
//                            List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
//                            return userIdsList.contains(payOrder.getOilPersonnelId());
//                        }
//                        if(StringUtils.isNotEmpty(device.getGunNo())){
//                            return true;
//                        }
                        if (StationDeviceManager.bindingType_staff.equals(device.getBindingType())) {
                            //当设备选择绑定员工，但未选择指定员工时，设备需播报或打印该设备所绑定的油站的所有订单
                            if (StringUtils.isBlank(device.getUserIds())) {
                                return true;
                            } else {
                                //当设备选择绑定员工且选择了指定的员工时，设备仅播报或打印所绑定员工的订单
                                List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
                                return userIdsList.contains(payOrder.getOilPersonnelId());
                            }
                        } else if (StationDeviceManager.bindingType_gun.equals(device.getBindingType())) {
                            //当设备选择绑定油枪时，但未选择指定油枪时，设备需播报或打印该设备所绑定的油站的所有订单
                            if (StringUtils.isBlank(device.getGunNo())) {
                                return true;
                            } else {
                                //当设备选择绑定油枪时且选择了指定油枪时，设备仅播报或打印所绑定油枪的订单
                                List<String> gunNoList = Arrays.asList(device.getGunNo().split(","));
                                return gunNoList.contains(payOrder.getOilGun());
                            }
                        }
                        return false;
                    }).collect(Collectors.toList());
                }
                List<StationDeviceManager> collect = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(manageWithUser)) {
                    collect = manageWithUser.stream().filter(m -> "3".equals(m.getDeviceType()) || "5".equals(m.getDeviceType())).collect(Collectors.toList());
                }
                stationDeviceManagerRes = CollectionUtil.isNotEmpty(collect) ? collect.get(0) : null /*stationDeviceManagers.get(0)*/;
                log.info("筛选绑定用户的小票机信息：{}", stationDeviceManagerRes);
            } catch (Exception e) {
                stationDeviceManagerRes = stationDeviceManagers.get(0);
                log.error(e.getMessage());
            }
            PrintEnum printEnum = null;
            String audio = "";
            if (stationDeviceManagerRes != null) {
                audio = stationDeviceManagerRes.getAudio();
                log.info("自定义语音audio:{}", audio);

                log.info("最终小票机信息：{}", stationDeviceManagerRes);
                String deviceFactory = stationDeviceManagerRes.getDeviceFactory();

                if (StringUtils.isNotEmpty(deviceFactory)) {
                    printEnum = PrintEnum.getByCode(deviceFactory);
                }
            }

            if (Objects.nonNull(printEnum)) {


                if (guKeFlag) {
                    if (StringUtils.isNotBlank(payOrder.getStationName())) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS2><center>" + payOrder.getStationName() + "</center></FS2><BR>");
                                content.append("<center>【顾客联】</center><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS2><center>" + payOrder.getStationName() + "</center></FS2><BR>");
                                content.append("<center>【顾客联】</center><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD><C><B>" + payOrder.getStationName() + "</B></C></BOLD><BR>");
                                content.append("<C>【顾客联】</C><BR>");
                                break;
                        }

                    }
                    if (payOrder.getReceivableAmt() != null) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS2>原价：" + payOrder.getReceivableAmt() + "元</FS2><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS2>原价：" + payOrder.getReceivableAmt() + "元</FS2><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD><B>原价：" + payOrder.getReceivableAmt() + "元</B></BOLD><BR>");
                                break;
                        }

                    }

                    if (StringUtils.isNotBlank(payOrder.getOrderNo())) {
                        content.append("订单号：" + payOrder.getOrderNo() + "<BR>");
                    }


                    if (StringUtils.isNotBlank(payOrder.getOilGun())) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS>油枪：" + payOrder.getOilGun() + "号枪</FS><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS>油枪：" + payOrder.getOilGun() + "号枪</FS><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD>油枪：" + payOrder.getOilGun() + "号枪</BOLD><BR>");
                                break;
                        }

                    }

                    if (StringUtils.isNotBlank(payOrder.getOilName())) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS>油品：" + payOrder.getOilName() + "</FS><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS>油品：" + payOrder.getOilName() + "</FS><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD>油品：" + payOrder.getOilName() + "</BOLD><BR>");
                                break;
                        }
                    }

                    if (StringUtils.isNotBlank(payOrder.getOilPirce())) {
                        content.append("单价：" + payOrder.getOilPirce() + "(元/升)<BR>");
                    }

                    if (StringUtils.isNotBlank(payOrder.getOrderLiters())) {
                        content.append("数量：" + payOrder.getOrderLiters() + "(L/kg)<BR>");
                    }

                    if (payOrder.getAmt() != null) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS>实付：" + payOrder.getAmt() + "元</FS><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS>实付：" + payOrder.getAmt() + "元</FS><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD>实付：" + payOrder.getAmt() + "元</BOLD><BR>");
                                break;
                        }
                    }

                    content.append("共优惠：" + new BigDecimal(String.valueOf(payOrder.getDiscountAmt())).add(new BigDecimal(String.valueOf(payOrder.getDiscountCouponAmt()))).setScale(2, RoundingMode.HALF_DOWN).stripTrailingZeros().toPlainString() + "元<BR>");
                    content.append("--------------------------------<BR>");
//
//                if(payOrder.getReceivableAmt() != null){
//                    content.append("应收款：" + payOrder.getReceivableAmt() + "<BR>");
//                }

                    if (StringUtils.isNotBlank(payOrder.getCustomerPhone())) {
                        content.append("手机号：" + DesensitizedUtil.mobilePhone(payOrder.getCustomerPhone()) + "<BR>");
                    }

                    if (StringUtils.isNotBlank(payTypeName)) {
                        content.append("支付方式：" + payTypeName + "<BR>");
                    }

                    if ("dzk".equals(payTyp)) {
//                    String electronicCardAmt = getElectronicCardAmt(payOrder);
                        content.append("电子卡余额：" + payOrder.getBalance() + "元<BR>");
                    }


                    CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                    customerPointsRecord.setOrderNo(payOrder.getOrderNo());
                    CustomerPointsRecord customerPointsRecordRes = customerPointsRecordService.getOne(customerPointsRecord);
                    log.info("订单号【{}】， 积分查询结果 : 【{}】", payOrder.getOrderNo(), customerPointsRecordRes);

                    if (Objects.isNull(payOrder.getIntegral())) {
                        payOrder.setIntegral("0");
                    }

                    String integral = Objects.nonNull(customerPointsRecordRes) ? customerPointsRecordRes.getIntegral().toString() : payOrder.getIntegral();

                    content.append("获得积分：" + integral + "<BR>");

                    PresentAmountRecord presentAmountRecord = new PresentAmountRecord();
                    presentAmountRecord.setOrderNo(payOrder.getOrderNo());
                    List<PresentAmountRecord> presentAmountRecords = presentAmountRecordMapper.query(presentAmountRecord);
                    BigDecimal presentAmount = CollectionUtil.isEmpty(presentAmountRecords) ? BigDecimal.ZERO : presentAmountRecords.get(0).getPresentAmount();
                    content.append("赠送金额：" + presentAmount + "元<BR>");

                    if (payOrder.getCreatedDate() != null) {
                        content.append("下单时间：" + sdf.format(payOrder.getCreatedDate()) + "<BR>");
                    }

                    if (payOrder.getPayDate() != null) {
                        content.append("付款时间：" + sdf.format(payOrder.getPayDate()) + "<BR>");
                    }


                    content.append("--------------------------------<BR>");


                    if (StringUtils.isNotBlank(payOrder.getOilPersonnel())) {
                        content.append("加油员：" + payOrder.getOilPersonnel() + "<BR>");
                    }

                    content.append("-------------------------<BR>");
                    content.append("打印时间：" + DateUtil.now() + "<BR>");
                    content.append("-------------------------<BR>");
                    content.append("谢谢惠顾！欢迎下次再来~<BR>");
                    content.append("<BR>");
                }
                if (shangHuflag) {
                    if (StringUtils.isNotBlank(payOrder.getStationName())) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS2><center>" + payOrder.getStationName() + "</center></FS2><BR>");
                                content.append("<center>【商户联】</center><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS2><center>" + payOrder.getStationName() + "</center></FS2><BR>");
                                content.append("<center>【商户联】</center><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD><C><B>" + payOrder.getStationName() + "</B></C></BOLD><BR>");
                                content.append("<C>【商户联】</C><BR>");
                                break;
                        }
                    }


                    if (payOrder.getReceivableAmt() != null) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS2>原价：" + payOrder.getReceivableAmt() + "元</FS2><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS2>原价：" + payOrder.getReceivableAmt() + "元</FS2><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD><B>原价：" + payOrder.getReceivableAmt() + "元</B></BOLD><BR>");
                                break;
                        }
                    }

                    if (StringUtils.isNotBlank(payOrder.getOrderNo())) {
                        content.append("订单号：" + payOrder.getOrderNo() + "<BR>");
                    }

                    if (StringUtils.isNotBlank(payOrder.getOilGun())) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS>油枪：" + payOrder.getOilGun() + "号枪</FS><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS>油枪：" + payOrder.getOilGun() + "号枪</FS><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD>油枪：" + payOrder.getOilGun() + "号枪</BOLD><BR>");
                                break;
                        }
                    }

                    if (StringUtils.isNotBlank(payOrder.getOilName())) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS>油品：" + payOrder.getOilName() + "</FS><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS>油品：" + payOrder.getOilName() + "</FS><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD>油品：" + payOrder.getOilName() + "</BOLD><BR>");
                                break;
                        }
                    }

                    if (StringUtils.isNotBlank(payOrder.getOilPirce())) {
                        content.append("单价：" + payOrder.getOilPirce() + "(元/升)<BR>");
                    }

                    if (StringUtils.isNotBlank(payOrder.getOrderLiters())) {
                        content.append("数量：" + payOrder.getOrderLiters() + "(L/kg)<BR>");
                    }

                    if (payOrder.getAmt() != null) {
                        switch (printEnum) {
                            case YILIANYUNK4:
                                content.append("<FS>实付：" + payOrder.getAmt() + "元</FS><BR>");
                                break;
                            case YILIANYUN:
                                content.append("<FS>实付：" + payOrder.getAmt() + "元</FS><BR>");
                                break;
                            case FEIE:
                                content.append("<BOLD>实付：" + payOrder.getAmt() + "元</BOLD><BR>");
                                break;
                        }
                    }

                    content.append("共优惠：" + MathUtil.add(new BigDecimal(String.valueOf(payOrder.getDiscountAmt())), new BigDecimal(String.valueOf(payOrder.getDiscountCouponAmt()))).setScale(2, RoundingMode.HALF_DOWN).stripTrailingZeros().toPlainString() + "元<BR>");
                    content.append("--------------------------------<BR>");
//
//                if(payOrder.getReceivableAmt() != null){
//                    content.append("应收款：" + payOrder.getReceivableAmt() + "<BR>");
//                }

                    if (StringUtils.isNotBlank(payOrder.getCustomerPhone())) {
                        content.append("手机号：" + DesensitizedUtil.mobilePhone(payOrder.getCustomerPhone()) + "<BR>");
                    }

                    if (StringUtils.isNotBlank(payTypeName)) {
                        content.append("支付方式：" + payTypeName + "<BR>");
                    }

                    if ("dzk".equals(payTyp)) {
//                    String electronicCardAmt = getElectronicCardAmt(payOrder);
                        content.append("电子卡余额：" + payOrder.getBalance() + "元<BR>");
                    }

                    CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                    customerPointsRecord.setOrderNo(payOrder.getOrderNo());
                    CustomerPointsRecord customerPointsRecordRes = customerPointsRecordService.getOne(customerPointsRecord);
                    log.info("订单号【{}】， 积分查询结果 : 【{}】", payOrder.getOrderNo(), customerPointsRecordRes);

                    if (Objects.isNull(payOrder.getIntegral())) {
                        payOrder.setIntegral("0");
                    }

                    String integral = Objects.nonNull(customerPointsRecordRes) ? customerPointsRecordRes.getIntegral().toString() : payOrder.getIntegral();

                    content.append("获得积分：" + integral + "<BR>");

                    PresentAmountRecord presentAmountRecord = new PresentAmountRecord();
                    presentAmountRecord.setOrderNo(payOrder.getOrderNo());
                    List<PresentAmountRecord> presentAmountRecords = presentAmountRecordMapper.query(presentAmountRecord);
                    BigDecimal presentAmount = CollectionUtil.isEmpty(presentAmountRecords) ? BigDecimal.ZERO : presentAmountRecords.get(0).getPresentAmount();
                    content.append("赠送金额：" + presentAmount + "元<BR>");


                    if (payOrder.getCreatedDate() != null) {
                        content.append("下单时间：" + sdf.format(payOrder.getCreatedDate()) + "<BR>");
                    }

                    if (payOrder.getPayDate() != null) {
                        content.append("付款时间：" + sdf.format(payOrder.getPayDate()) + "<BR>");
                    }


                    content.append("--------------------------------<BR>");


                    if (StringUtils.isNotBlank(payOrder.getOilPersonnel())) {
                        content.append("加油员：" + payOrder.getOilPersonnel() + "<BR>");
                    }

                    content.append("-------------------------<BR>");
                    content.append("打印时间：" + DateUtil.now() + "<BR>");
                    content.append("-------------------------<BR>");
                    content.append("谢谢惠顾！欢迎下次再来~<BR>");
                    content.append("<BR>");
                }
//            content.append("<BR>");
//            content.append("<BR>");

                System.out.println(content.toString());

                switch (printEnum) {
                    case YILIANYUNK4:
                        Integer isPrintK4 = stationDeviceManagerRes.getIsPrint();
                        HashMap<String, String> k4AudioMap = new HashMap<>();
                        boolean hasPhoneK4 = StringUtils.isNotBlank(payOrder.getMobilePhone());

                        StringBuffer sbVoice = new StringBuffer();
                        try {
                            String[] split = audio.split(";");

                            //加油语音
                            String oilOrderAudio = split[0];
                            List<String> oilOrderAudioList = Arrays.asList(oilOrderAudio.split(","));
                            log.info("语音内容{}", oilOrderAudioList);
                            if (CollectionUtil.isNotEmpty(oilOrderAudioList)) {
                                for (String audioContent : oilOrderAudioList) {

                                    if ("手机尾号".equals(audioContent)) {
                                        log.info("手机尾号{}", payOrder.getMobilePhone());
                                        if (StringUtils.isNotBlank(payOrder.getMobilePhone())) {
                                            String mobilePhone = payOrder.getMobilePhone().substring(7, 11);
                                            log.info("mobilePhone{}", mobilePhone);
                                            char[] chars = mobilePhone.toCharArray();
                                            log.info("chars{}", chars);
                                            sbVoice.append("<VN>").append(1).append("</VN>");
                                            for (char aChar : chars) {
                                                sbVoice.append("<VD>").append(aChar).append("</VD>");
                                            }
                                        }

                                    } else if ("加油金额".equals(audioContent)) {
                                        sbVoice.append("<VN>").append(2).append("</VN>")
                                                .append("<VD>").append(BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString()).append("</VD>").append("<VN>0</VN>");
                                    } else if ("支付金额".equals(audioContent)) {
                                        sbVoice.append("<VN>").append(3).append("</VN>")
                                                .append("<VD>").append(BigDecimal.valueOf(payOrder.getAmt()).stripTrailingZeros().toPlainString()).append("</VD>").append("<VN>0</VN>");
                                    } else if ("枪号".equals(audioContent)) {
                                        sbVoice.append("<VN>").append(4).append("</VN>")
                                                .append("<VD>").append(payOrder.getOilGun()).append("</VD>");
                                    } else if ("油品".equals(audioContent)) {
                                        if (payOrder.getOilName().contains("-")) {
                                            sbVoice.append("<VN>").append(9).append("</VN>")
                                                    .append("<VD>").append(payOrder.getOilName().replace("-", "")).append("</VD>");
                                        } else {
                                            sbVoice.append("<VN>").append(5).append("</VN>")
                                                    .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                                        }
                                    }

                                }
                            } else {
                                sbVoice.append("<VN>1</VN>");
                                if (StringUtils.isNotBlank(payOrder.getMobilePhone())) {
                                    String mobilePhone = payOrder.getMobilePhone().substring(7, 11);
                                    log.info("mobilePhone{}", mobilePhone);
                                    char[] chars = mobilePhone.toCharArray();
                                    log.info("chars{}", chars);
                                    sbVoice.append("<VN>").append(1).append("</VN>");
                                    for (char aChar : chars) {
                                        sbVoice.append("<VD>").append(aChar).append("</VD>");
                                    }
                                }
                                sbVoice = sbVoice.append("<VN>1</VN>").append("<VD>").append(BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString()).append("</VD>")
                                        .append("<VN>4</VN>").append("<VD>").append(payOrder.getOilGun()).append("</VD>");
                                if (payOrder.getOilName().contains("-")) {
                                    sbVoice = sbVoice.append("<VN>").append(9).append("</VN>")
                                            .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                                } else {
                                    sbVoice = sbVoice.append("<VN>").append(5).append("</VN>")
                                            .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                                }
                            }

                            log.info("K4播报语音：{}", sbVoice);
                        } catch (Exception e) {
                            sbVoice = sbVoice.append("<VN>2</VN>").append("<VD>").append(BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString()).append("</VD>").append("<VN>0</VN>")
                                    .append("<VN>4</VN>").append("<VD>").append(payOrder.getOilGun()).append("</VD>");

                            if (payOrder.getOilName().contains("-")) {
                                sbVoice = sbVoice.append("<VN>").append(9).append("</VN>")
                                        .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                            } else {
                                sbVoice = sbVoice.append("<VN>").append(5).append("</VN>")
                                        .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                            }
                        }

                        StringBuffer finalContentVoice;
                        if (Objects.nonNull(isPrintK4) && isPrintK4.equals(0)) {
                            finalContentVoice = sbVoice;
                        } else {
                            String ylyK4Content = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                            finalContentVoice = sbVoice.append(ylyK4Content);
                        }
                        //初始化控制器类
                        Methods mK4 = Methods.getInstance();
                        Object tokenK4 = redisCacheUtil.getCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId());

                        Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                        String printK4;
                        if (Objects.nonNull(tokenK4)) {
                            printK4 = mK4.print(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getDeviceNo(), finalContentVoice.toString(), random6K4.toString(), tokenK4.toString());
                            log.info("小票机返回值{}", printK4);
                            JSONObject jsonK4 = new JSONObject(printK4);

                            if ("0".equals(jsonK4.getString("error"))) {
                                if (isPrintK4.equals(1)) {
                                    changeOrderPrintStatus(payOrder.getOrderNo());
                                }
                                break;
                            }

                        }
                        //初始化终端信息
                        mK4.init(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getClientSecret());
                        //获取token
                        String refreshTokenK4 = mK4.getFreedomToken();
                        //存入redis
                        redisCacheUtil.setCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId(), refreshTokenK4, 30, TimeUnit.DAYS);


                        printK4 = mK4.print(stationDeviceManagerRes.getDeviceNo(), finalContentVoice.toString(), random6K4.toString());
                        log.info("小票机返回值2{}", printK4);
                        JSONObject jsonK4 = new JSONObject(printK4);
                        if ("0".equals(jsonK4.getString("error")) && isPrintK4.equals(1)) {
                            changeOrderPrintStatus(payOrder.getOrderNo());
                        }


                        break;
                    case YILIANYUN:
                        Integer isPrint = stationDeviceManagerRes.getIsPrint();
                        HashMap<String, String> audioMap = new HashMap<>();
                        String phoneTail = "";
                        boolean hasPhone = StringUtils.isNotBlank(payOrder.getCustomerPhone());
                        if (hasPhone && Validator.isMobile(payOrder.getCustomerPhone())) {
                            phoneTail = payOrder.getCustomerPhone().substring(7, 11);
                            audioMap.put("手机尾号", phoneTail);
                        }
                        audioMap.put("加油金额", BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString() + "元");
                        audioMap.put("支付金额", BigDecimal.valueOf(payOrder.getAmt()).stripTrailingZeros().toPlainString() + "元");
                        audioMap.put("枪号", payOrder.getOilGun());

                        String finalOilName = "";
                        if (StringUtils.isNotEmpty(payOrder.getOilName())) {
                            finalOilName = payOrder.getOilName().replace("#", "号");
                        }
                        audioMap.put("油品", finalOilName);

                        StringBuffer sb = new StringBuffer();
                        try {
                            String[] split = audio.split(";");

                            //加油语音
                            String oilOrderAudio = split[0];
                            List<String> oilOrderAudioList = Arrays.asList(oilOrderAudio.split(","));
                            sb.append("<audio>");
                            for (String audioContent : oilOrderAudioList) {
                                if (StringUtils.equals("手机尾号", audioContent) && !hasPhone) {
                                    continue;
                                }
                                sb.append(audioContent + audioMap.get(audioContent));
                            }
                            sb.append("</audio>");
                            log.info("播报语音：{}", sb);
                        } catch (Exception e) {
                            sb = new StringBuffer();
                            sb.append("<audio>");
                            if (hasPhone) {
                                sb.append("手机尾号").append(phoneTail);
                            }
                            sb.append("支付金额").append(BigDecimal.valueOf(payOrder.getAmt()).stripTrailingZeros().toPlainString()).append("元")
                                    .append("加油金额").append(BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString()).append("元")
                                    .append(payOrder.getOilGun()).append("号油枪")
                                    .append(payOrder.getOilName()).append("号油,</audio>");
                        }

                        StringBuffer finalContent;
                        if (Objects.nonNull(isPrint) && isPrint.equals(0)) {
                            finalContent = sb;
                        } else {
                            String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                            finalContent = sb.append(ylyContent);
                        }
                        //初始化控制器类
                        Methods m = Methods.getInstance();
                        Object token = redisCacheUtil.getCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId());

                        Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                        String print;
                        if (Objects.nonNull(token)) {
                            print = m.print(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getDeviceNo(), finalContent.toString(), random6.toString(), token.toString());
                            log.info("小票机返回值{}", print);
                            JSONObject json = new JSONObject(print);

                            if ("0".equals(json.getString("error"))) {
                                if (isPrint.equals(1)) {
                                    changeOrderPrintStatus(payOrder.getOrderNo());
                                }
                                break;
                            }

                        }
                        //初始化终端信息
                        m.init(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getClientSecret());
                        //获取token
                        String refreshToken = m.getFreedomToken();
                        //存入redis
                        redisCacheUtil.setCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId(), refreshToken, 30, TimeUnit.DAYS);


                        print = m.print(stationDeviceManagerRes.getDeviceNo(), finalContent.toString(), random6.toString());
                        log.info("小票机返回值2{}", print);
                        JSONObject json = new JSONObject(print);
                        if ("0".equals(json.getString("error")) && isPrint.equals(1)) {
                            changeOrderPrintStatus(payOrder.getOrderNo());
                        }

                        break;
                    case FEIE:
                        String result = FeiEPrinterUtil.printReceipt(stationDeviceManagerRes.getDeviceNo(), content.toString());
                        JSONObject resJson = new JSONObject(result);
                        if ("ok".equals(resJson.get("msg"))) {
                            changeOrderPrintStatus(payOrder.getOrderNo());
                        }

                        break;
                    default:
                        log.info("没有配置小票机，打印失败");
                        break;
                }
            }
            //音箱云播报
            StationDeviceManager voiceDevice = null;
            StationDeviceManager voiceDevice2 = null;
            for (StationDeviceManager deviceManager : manageWithUser) {
                if ("4".equals(deviceManager.getDeviceType())) {
                    voiceDevice = deviceManager;
                }
                if ("8".equals(deviceManager.getDeviceType())) {
                    voiceDevice2 = deviceManager;
                }
            }

            if (Objects.nonNull(voiceDevice)) {

                StringBuilder voiceContent = new StringBuilder();
                String voice = voiceDevice.getAudio();
                String[] split = voice.split(";");
                if (!(split.length > 0)) {
                    String oilName = payOrder.getOilName().replace("#", "号");
                    String oilGun = payOrder.getOilGun();
                    Double amt = payOrder.getReceivableAmt();
                    voiceContent.append(oilName).append(oilGun).append("号枪").append(amt).append("元");
                } else {


                    //加油语音
                    String oilOrderAudio = split[0];
                    List<String> voiceList = Arrays.asList(oilOrderAudio.split(","));

                    HashMap<Object, Object> voiceMap = new HashMap<>();
                    voiceMap.put("油品名称", payOrder.getOilName().replace("#", "号,"));
                    voiceMap.put("枪号", payOrder.getOilGun() + "号枪,");
                    voiceMap.put("应付金额", payOrder.getReceivableAmt().toString() + "元,");
                    voiceMap.put("实付金额", payOrder.getAmt().toString() + "元,");


                    for (String audioContent : voiceList) {
                        voiceContent.append(voiceMap.get(audioContent));
                    }

                }

                log.info("云播报设备播报内容{}", voiceContent);
                List<StationDeviceManager> collect = manageWithUser.stream().filter(m -> "4".equals(m.getDeviceType())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect)) {
                    log.info("云喇叭信息{}", collect.get(0));
                    deviceService.voiceBroadcast(collect.get(0).getDeviceNo(), voiceContent.toString());
                }
            }
            if (Objects.nonNull(voiceDevice2)) {
                String voice = voiceDevice2.getAudio();

                StringBuilder voiceContent = new StringBuilder();
                List<StationDeviceManager> collect2 = manageWithUser.stream().filter(m -> "8".equals(m.getDeviceType())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect2)) {
                    log.info("吹吹大喇叭{}", collect2.get(0));
                    Random random = new Random();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

/*                    String voiceBroadcastLoudspeaker( String msgId,String sn,String transactionId,String content,String totalFee,String payType,String discountFee,String attach
                            ,String lang,String nonce,String timestamp
    ) ;*/
                    String oilName = payOrder.getOilName().replace("#", "号");
                    String oilGun = payOrder.getOilGun();
                    Double amt = payOrder.getReceivableAmt();
                    voiceContent.append(oilName).append("号").append(oilGun).append("号枪").append(amt).append("元");

                    if (StringUtils.isNotEmpty(voice)) {
                        String s = voice.split(";")[0];
                        if (StringUtils.isNotEmpty(s)) {
                            String[] voiceList = s.split(",");
                            HashMap<Object, Object> voiceMap = new HashMap<>();
                            voiceMap.put("油品名称", payOrder.getOilName().replace("#", "").replace("国标", "").replace("号", "") + "号,");
                            voiceMap.put("枪号", payOrder.getOilGun() + "号枪,");
                            voiceMap.put("应付金额", payOrder.getReceivableAmt().toString() + "元,");
                            voiceMap.put("实付金额", payOrder.getAmt().toString() + "元,");
                            voiceContent = new StringBuilder();
                            for (String audioContent : voiceList) {
                                voiceContent.append(voiceMap.get(audioContent));
                            }
                        }

                    }

                    deviceService.voiceBroadcastLoudspeaker(payOrder.getOrderNo(), collect2.get(0).getDeviceNo(),
                            payOrder.getOrderNo(), voiceContent.toString(), payOrder.getReceivableAmt().toString(), "02",
                            payOrder.getDiscountAmt().toString(), null, null, random.nextInt(10) + "", simpleDateFormat.format(new Date()));
                }
            }
        }
//        catch (EndingException e)
//        {
//            logger.info(e.getMessage());
//
//        }
        catch (Exception e) {
            logger.error(">pushConsumeToUser", e);
        }

    }

    private void changeOrderPrintStatus(String orderNo) {
        log.info("修改订单打印状态,订单号：{}", orderNo);
        PayOrder payOrderStatus = new PayOrder();
        payOrderStatus.setOrderNo(orderNo);
        payOrderStatus.setIsPrint(1);
        payOrderService.updatePayOrder(payOrderStatus);
    }

    @Async
    @Override
    public void pushConsumeToEmployees(PayOrder payOrder) {
        try {
            if (payOrder.getStationId() == null) {
                return;
            }
            List<SysUser> sysUserList = sysUserService.selectSysUserListForPush(SysUser.builder().stationId("" + payOrder.getStationId()).build());

            if (sysUserList.size() == 0) {
                return;
            }

            // 查找需要推送的userids
            List<String> idList = sysUserList.stream().filter((e) ->
            {
                System.out.println(e.getUserId());
                if (StringUtils.isBlank(e.getPushUserIds())) {
                    return false;
                }

                if (StringUtils.isBlank(payOrder.getOilPersonnelId())) {
                    return "1".equals(e.getNullSendFlag());
                }

                if (payOrder.getOilPersonnelId().equals("" + e.getUserId())) {
                    return true;
                }
                return false;
            }).map(e ->
                    Arrays.asList(e.getPushUserIds().split(","))
            ).findFirst().orElseGet(ArrayList::new);

            // 查找符合条件的加油员并推送
            sysUserList.stream().filter(e ->
                    {
                        if (!"1".equals(e.getEmpPushFlag())) {
                            return false;
                        }
                        if (StringUtils.isBlank(e.getPushOpenid())) {
                            return false;
                        }

                        return idList.contains("" + e.getUserId());
                    }
            ).forEach(e -> {
                System.out.println(e.getPushOpenid());
                doPushConsumeToEmployees(payOrder, e.getPushOpenid());
            });


        } catch (Exception e) {
            logger.error(">pushEmployees", e);
        }
    }


    private void doPushConsumeToEmployees(PayOrder order, String openid) {
        try {

            if (order.getEnterpriseId() == null) {
                return;
            }
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(order.getEnterpriseId());
            String gzhAppId = enterprise.getGzhAppId();
            String gzhAppSecret = enterprise.getGzhAppSecret();


            GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
            gzhNewsTemplate.setTemplateType("4");
            gzhNewsTemplate.setStationId(order.getEnterpriseId());
            GzhNewsTemplate gzhNewsTemplateInfo = getGzhNewsTemplate(gzhNewsTemplate);

            WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
            wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
            wxTemplateMsg.setTouser(openid);


            Map<String, WxTemplateData> templateDataMap = new HashMap<>();
            String payTyp = order.getPayType();
            StringBuilder payTypeName = new StringBuilder("");
            switch (payTyp) {
                case "wx":
                    payTypeName.append("微信支付");
                    break;
                case "zfb":
                    payTypeName.append("支付宝支付");
                    break;
                case "dzk":
                    payTypeName.append("电子卡支付");
                    break;
                case "xj":
                    payTypeName.append("现金支付");
                    break;
                case "hyk":
                    payTypeName.append("实体卡");
                    break;
                case "yl":
                    payTypeName.append("银联支付");
                    break;
                default:
            }
            StringBuilder remarkString = new StringBuilder("");
            remarkString.append("\n").append("系统订单监控中~");

            templateDataMap.put("first", WxTemplateData.builder().value("客户" + order.getConsumer() + order.getCustomerPhone() + "在" + order.getStationName() + "完成支付").build());
            templateDataMap.put("time", WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
            templateDataMap.put("org", WxTemplateData.builder().value(order.getStationName()).build());
            templateDataMap.put("type", WxTemplateData.builder().value(payTypeName.toString()).build());
            templateDataMap.put("money", WxTemplateData.builder().value("实付" + order.getAmt() + "元，应付" + order.getReceivableAmt() + "元").build());
            templateDataMap.put("remark", WxTemplateData.builder().value(remarkString.toString()).build());
            templateDataMap.put("point", WxTemplateData.builder().value("暂不可监控").build());

            wxTemplateMsg.setData(templateDataMap);
            wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);
            logger.info(">pushConsumeToEmployees" + "-" + openid + "--" + "消息推送完成");
        } catch (Exception e) {
            logger.error(">pushEmployees", e);
        }
    }

    @Override
    @Async
    public void broadcastCancelOrder(BroadcastCancelOrderDTO cancelOrderDTO) {
        StationDeviceManager form = new StationDeviceManager();
        form.setStationId(cancelOrderDTO.getStationId());
        List<StationDeviceManager> deviceList = posMachineMapper.getStationDeviceManagerList(form);
        List<BroadcastCancelOrderDTO.Gun> gunList;
        if (CollectionUtils.isNotEmpty(cancelOrderDTO.getGunList())) {
            gunList = cancelOrderDTO.getGunList();
        } else {
            if (StringUtils.isNotBlank(cancelOrderDTO.getGunName()) || StringUtils.isNotBlank(cancelOrderDTO.getOilPersonId())) {
                BroadcastCancelOrderDTO.Gun gun = new BroadcastCancelOrderDTO.Gun();
                gun.setGunName(cancelOrderDTO.getGunName());
                gun.setOilPersonId(cancelOrderDTO.getOilPersonId());
                gunList = Collections.singletonList(gun);
            } else {
                gunList = Collections.emptyList();
            }
        }
        if (CollectionUtils.isEmpty(gunList)) {
            return;
        }
        for (StationDeviceManager deviceManager : deviceList) {
            String deviceType = deviceManager.getDeviceType();
            if (!StringUtils.equalsAny(deviceType, "3", "4", "8")) {
                continue;
            }
            String bindingType = deviceManager.getBindingType();
            for (BroadcastCancelOrderDTO.Gun gun : gunList) {
                cancelOrderDTO.setGunName(gun.getGunName());
                cancelOrderDTO.setOilPersonId(gun.getOilPersonId());
                if (StationDeviceManager.bindingType_staff.equals(bindingType)) {
                    //当设备选择绑定员工，但未选择指定员工时，设备需播报或打印该设备所绑定的油站的所有订单
                    if (StringUtils.isBlank(deviceManager.getUserIds())) {
                        sendBroadcastCancelOrderToDevice(deviceManager, cancelOrderDTO);
                    } else {
                        //当设备选择绑定员工且选择了指定的员工时，设备仅播报或打印所绑定员工的订单
                        if (StringUtils.isBlank(gun.getOilPersonId())) {
                            continue;
                        }
                        if (StringUtils.contains(deviceManager.getUserIds(), gun.getOilPersonId())) {
                            sendBroadcastCancelOrderToDevice(deviceManager, cancelOrderDTO);
                        }
                    }
                } else if (StationDeviceManager.bindingType_gun.equals(bindingType)) {
                    //当设备选择绑定油枪时，但未选择指定油枪时，设备需播报或打印该设备所绑定的油站的所有订单
                    if (StringUtils.isBlank(deviceManager.getGunNo())) {
                        sendBroadcastCancelOrderToDevice(deviceManager, cancelOrderDTO);
                    } else {
                        //当设备选择绑定油枪时且选择了指定油枪时，设备仅播报或打印所绑定油枪的订单
                        if (StringUtils.isBlank(gun.getGunName())) {
                            continue;
                        }
                        if (StringUtils.contains(deviceManager.getGunNo(), gun.getGunName())) {
                            sendBroadcastCancelOrderToDevice(deviceManager, cancelOrderDTO);
                        }
                    }
                }
            }
        }
    }

    private void sendBroadcastCancelOrderToDevice(StationDeviceManager deviceManager, BroadcastCancelOrderDTO cancelOrderDTO) {
        switch (deviceManager.getDeviceType()) {
//            case "1":
//                pos(deviceManager,cancelOrderDTO);
//                break;
            case "3":
                xiaoPiaoJi(deviceManager, cancelOrderDTO);
                break;
            case "4":
                yunLaBa(deviceManager, cancelOrderDTO);
                break;
            case "8":
                yunYinXiang(deviceManager, cancelOrderDTO);
                break;
        }
    }

    private void xiaoPiaoJi(StationDeviceManager deviceManager, BroadcastCancelOrderDTO cancelOrderDTO) {
        String deviceFactory = deviceManager.getDeviceFactory();
        PrintEnum printEnum = null;
        if (StringUtils.isNotEmpty(deviceFactory)) {
            printEnum = PrintEnum.getByCode(deviceFactory);
        }
        if (printEnum != PrintEnum.YILIANYUN) {
            // 易连云k4播不了
            return;
        }
        if (Objects.nonNull(printEnum)) {
            String voiceContent = null;
            switch (printEnum) {
                case YILIANYUNK4:
                    // todo
                    voiceContent = String.format("<VN>4</VN><VD>%s</VD><VI>043</VI><VI>039</VI>", cancelOrderDTO.getGunName());
                    break;
                case YILIANYUN:
                    voiceContent = "<audio>" + getCancelOrderVoiceContent(cancelOrderDTO) + "</audio>";
                    break;
            }
            switch (printEnum) {
                case YILIANYUNK4:
                    //初始化控制器类
                    Methods mK4 = Methods.getInstance();
                    Object tokenK4 = redisCacheUtil.getCacheObject("STATION:DEVICE:" + deviceManager.getClientId());
                    Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                    String printK4;
                    if (Objects.nonNull(tokenK4)) {
                        printK4 = mK4.print(deviceManager.getClientId(), deviceManager.getDeviceNo(), voiceContent, random6K4.toString(), tokenK4.toString());
                        log.info("小票机返回值{}", printK4);
                        JSONObject jsonK4 = new JSONObject(printK4);
                        if ("0".equals(jsonK4.getString("error"))) {
                            break;
                        }
                    }
                    //初始化终端信息
                    mK4.init(deviceManager.getClientId(), deviceManager.getClientSecret());
                    //获取token
                    String refreshTokenK4 = mK4.getFreedomToken();
                    //存入redis
                    redisCacheUtil.setCacheObject("STATION:DEVICE:" + deviceManager.getClientId(), refreshTokenK4, 30, TimeUnit.DAYS);
                    printK4 = mK4.print(deviceManager.getDeviceNo(), voiceContent, random6K4.toString());
                    log.info("小票机返回值2{}", printK4);
                    break;
                case YILIANYUN:
                    //初始化控制器类
                    Methods m = Methods.getInstance();
                    Object token = redisCacheUtil.getCacheObject("STATION:DEVICE:" + deviceManager.getClientId());
                    Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                    String print;
                    if (Objects.nonNull(token)) {
                        print = m.print(deviceManager.getClientId(), deviceManager.getDeviceNo(), voiceContent, random6.toString(), token.toString());
                        log.info("小票机返回值{}", print);
                        JSONObject json = new JSONObject(print);
                        if ("0".equals(json.getString("error"))) {
                            break;
                        }
                    }
                    //初始化终端信息
                    m.init(deviceManager.getClientId(), deviceManager.getClientSecret());
                    //获取token
                    String refreshToken = m.getFreedomToken();
                    //存入redis
                    redisCacheUtil.setCacheObject("STATION:DEVICE:" + deviceManager.getClientId(), refreshToken, 30, TimeUnit.DAYS);
                    print = m.print(deviceManager.getDeviceNo(), voiceContent, random6.toString());
                    log.info("小票机返回值2{}", print);
                    break;
            }
        }
    }

    private void yunLaBa(StationDeviceManager deviceManager, BroadcastCancelOrderDTO cancelOrderDTO) {
        String voiceContent = getCancelOrderVoiceContent(cancelOrderDTO);
        deviceService.syncVoiceBroadcast(deviceManager.getDeviceNo(), voiceContent);
    }

    private void yunYinXiang(StationDeviceManager deviceManager, BroadcastCancelOrderDTO cancelOrderDTO) {
        String voiceContent = getCancelOrderVoiceContent(cancelOrderDTO);
        String time = LocalDateTimeUtil.parse(LocalDateTime.now(), LocalDateTimeUtil.YYYYMMDDHHMMSS);
        String msgId = String.valueOf(MobilePhoneUtil.nextId());
        deviceService.voiceBroadcastLoudspeaker(msgId, deviceManager.getDeviceNo(), msgId, voiceContent, "0", "02",
                null, null, null, "123456", time);
    }

    private void pos(StationDeviceManager deviceManager, BroadcastCancelOrderDTO cancelOrderDTO) {
//        Long aLong = redisTemplate.opsForList().rightPush("ss", cancelOrderDTO.getGunName());
    }

    private String getCancelOrderVoiceContent(BroadcastCancelOrderDTO cancelOrderDTO) {
        return String.format("%s号枪取消支付", cancelOrderDTO.getGunName());
    }

    /**
     * 自定义打印小票测试方法
     *
     * @param payOrder
     */
    @Override
    public void printOrderReceipt(PayOrder payOrder) {
        payOrder = payOrderService.selectOrderInfoByOrdNo("1703823134730943845");
//        Map<String,Object> context = new HashMap<>();
//        context.put("order", payOrder);
//        context.put("payTypeName", "payTypeName");
//        context.put("printTime", new Date());
//        context.put("totalDiscountAmt", MathUtil.add(BigDecimal.valueOf(payOrder.getDiscountAmt()), BigDecimal.valueOf(payOrder.getDiscountCouponAmt())).setScale(2, RoundingMode.DOWN));
//        context.put("startLineWrap",true);
//        StringBuilderWriter builderWriter = new StringBuilderWriter();
//        receiptSectionService.mergeTemplate(173L,ReceiptType.CONSUME_CUSTOMER_UNION,PrintEnum.YILIANYUNK4,context,builderWriter);
//        log.info("ssssss\n{}",builderWriter);
        this.feiePush(payOrder);
//        this.feiePush2(payOrder);
    }

    @Override
    public String getOrderReceiptString(String orderNo, String deviceFactory, String printType, boolean his) {
        PayOrder payOrder;
        if (his) {
            payOrder = payOrderHistoryMapper.selectOrderInfoByOrdNo(orderNo);
        } else {
            payOrder = payOrderService.selectOrderInfoByOrdNo(orderNo);
        }
        if (payOrder == null) {
            throw new CustomException("订单未找到");
        }
        if (Objects.isNull(payOrder.getIntegral())) {
            payOrder.setIntegral("0");
        }
        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
        customerPointsRecord.setOrderNo(payOrder.getOrderNo());
        CustomerPointsRecord customerPointsRecordRes = customerPointsRecordService.getOne(customerPointsRecord);
        log.info("订单号【{}】， 积分查询结果 : 【{}】", payOrder.getOrderNo(), customerPointsRecordRes);
        if (Objects.nonNull(customerPointsRecordRes)) {
            payOrder.setIntegral(MathUtil.add(null, customerPointsRecordRes.getIntegral()).toString());
        }
        StringBuilderWriter builderWriter = new StringBuilderWriter();
        writeOrderReceiptString(payOrder, new Date(), PrintEnum.getByCode(deviceFactory), printType, true, builderWriter);
        return builderWriter.toString();
    }

    @Override
    public String getClassSettlementReceiptString(Map<String, Object> printInfo) {
        log.info("getClassSettlementReceiptString:{}", JSON.toJSONString(printInfo));
        if (null != printInfo) {
            StringBuilderWriter builderWriter = new StringBuilderWriter();
            receiptSectionService.mergeTemplate(Long.valueOf(printInfo.get("enterpriseId").toString()), ReceiptType.CLASS_SETTLEMENT, PrintEnum.getByCode(printInfo.get("printType").toString()), printInfo, builderWriter);
            log.info("getClassSettlementReceiptString.builderWriter:{}", builderWriter.toString());
            return builderWriter.toString();
        }
        return null;
    }

    /**
     * 获取订单小票字符串
     */
    private void writeOrderReceiptString(PayOrder payOrder, Date printTime, PrintEnum printEnum, String printType, boolean extraPrint, Writer writer) {
        if (payOrder == null) {
            throw new CustomException("订单未找到");
        }
        String payTyp = payOrder.getPayType();
        String payTypeName = null;
        switch (payTyp) {
            case "wx":
                payTypeName = "微信支付";
                break;
            case "zfb":
                payTypeName = "支付宝支付";
                break;
            case "dzk":
                payTypeName = "电子卡支付";
                break;
            case "xj":
                payTypeName = "现金支付";
                break;
            case "dkq":
                payTypeName = "实体卡";
                PhysicalCardBalance param = new PhysicalCardBalance();
                param.setBalanceNo(payOrder.getOrderNo());
                PhysicalCardBalance result = physicalCardBalanceService.selectPhysicalCardBalance(param);
                if (null!=result){
                    payOrder.setBalance(result.getBalanceAmount());
                }
                break;
            case "yl":
                payTypeName = "银联支付";
                break;
            case "cdk":
                payTypeName = "车队卡";

                break;
            case "pos":
                payTypeName = "POS机";
                break;
            case "yhk":
                payTypeName = "银行卡";
                break;
            default:
                break;
        }
        Map<String, Object> context = new HashMap<>();
        boolean guKeFlag = true;
        boolean shangHuflag = true;
        if ("1".equals(printType)) {
            shangHuflag = false;
        }
        if ("2".equals(printType)) {
            guKeFlag = false;
        }
        context.put("order", payOrder);
        context.put("payTypeName", payTypeName);
        context.put("printTime", printTime);
        context.put("totalDiscountAmt", MathUtil.add(BigDecimal.valueOf(payOrder.getDiscountAmt()), BigDecimal.valueOf(payOrder.getDiscountCouponAmt())).setScale(2, RoundingMode.DOWN));
        context.put("extraPrint", extraPrint);
        if (guKeFlag) {
            receiptSectionService.mergeTemplate(Long.valueOf(payOrder.getEnterpriseId()), ReceiptType.CONSUME_CUSTOMER_UNION, printEnum, context, writer);
        }
        if (shangHuflag) {
//            context.put("startLineWrap", guKeFlag);
            receiptSectionService.mergeTemplate(Long.valueOf(payOrder.getEnterpriseId()), ReceiptType.CONSUME_MERCHANT_UNION, printEnum, context, writer);
        }
    }

    public String writeBanJieReceiptString() {
        StringBuilderWriter builderWriter = new StringBuilderWriter();
        Map<String, Object> baseSetting = new HashMap<>(); // 基础设置

        baseSetting.put("stationName", "芝麻香油站"); //油站名称
        baseSetting.put("successioDate", "2023-09-12 19:59:43"); // 接班时间
        baseSetting.put("shiftDate", "2023-09-13 19:59:43"); // 交班时间
        baseSetting.put("submitter", "靓仔！"); // 交接人
        Map<String, Object> totalSum = new HashMap<>(); // 合计汇总
        totalSum.put("receivableAmt", 20200.33); // 消费应收总金额
        totalSum.put("receivableQty", 177);// 消费应收总笔数
        totalSum.put("discountAmt", 2020.33);// 消费优惠总金额
        totalSum.put("discountQty", 130);// 消费优惠总笔数
        totalSum.put("receivedAmt", 2020.33);// 消费实收总金额
        totalSum.put("receivedQty", 177);// 消费实收总笔数
        totalSum.put("consumptionRefundAmt", 101.12);// 消费消费退款
        totalSum.put("rechargeRefundAmt", 101.21);// 充值退款
        totalSum.put("refundAmt", 202.33);// 退款总金额
        totalSum.put("refundQty", 2);// 退款总笔数
        totalSum.put("dzkSavingsAtm", 36473.66);// 电子卡储值额
        totalSum.put("hykSavingsAtm", 3748.33);// 实体卡储值额
        totalSum.put("cdkSavingsAtm", 8372.22);// 车队卡储值额
        totalSum.put("savingsAtm", 48594.21);// 储值合计
        totalSum.put("salesVolume", 7878.26);// 销售量(L/KG)
        totalSum.put("salesQty", 177);// 销售笔数
        totalSum.put("arrivalAmt", 50392.33);// 到账总金额
        totalSum.put("arrivalQty", 177);// 到账笔数
        Map<String, Object> details = new HashMap<>(); // 消费收款明细
        details.put("payType", "微信");
        details.put("count", 100);
        details.put("amount", 1000);
        List collectionDetailsList = new ArrayList();
        collectionDetailsList.add(details);
        collectionDetailsList.add(details);
        collectionDetailsList.add(details);
        Map<String, Object> rechargeInfo = new HashMap<>(); // 充值汇总
        rechargeInfo.put("rechargeType", "微信");
        rechargeInfo.put("count", 12);
        rechargeInfo.put("amount", 123);
        List rechargeSum = new ArrayList();
        rechargeSum.add(rechargeInfo);
        rechargeSum.add(rechargeInfo);
        rechargeSum.add(rechargeInfo);
        Map<String, Object> oilInfo = new HashMap<>(); // 油品汇总
        oilInfo.put("oilName", "95#");
        oilInfo.put("count", 13);
        oilInfo.put("amount", 123.08);
        List oilSum = new ArrayList();
        oilSum.add(oilInfo);
        oilSum.add(oilInfo);
        oilSum.add(oilInfo);
        Map<String, Object> employeeInfo = new HashMap<>(); // 员工汇总
        employeeInfo.put("employeeName", "张三");
        employeeInfo.put("count", 13);
        employeeInfo.put("amount", 145.89);
        List employeeSum = new ArrayList(); // 员工汇总
        employeeSum.add(employeeInfo);
        employeeSum.add(employeeInfo);
        employeeSum.add(employeeInfo);
        Map<String, Object> pageTail = new HashMap<>(); // 页尾
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        pageTail.put("printTime", sdf.format(new Date()));
        Map<String, Object> context = new HashMap<>();
        context.put("baseSetting", baseSetting);
        context.put("totalSum", totalSum);
        context.put("collectionDetailsList", collectionDetailsList);
        context.put("rechargeSum", rechargeSum);
        context.put("oilSum", oilSum);
        context.put("employeeSum", employeeSum);
        context.put("pageTail", pageTail);
        context.put("extraPrint", true); // 是否补打
        receiptSectionService.mergeTemplate(0l, ReceiptType.CLASS_SETTLEMENT, PrintEnum.getByCode("3"), context, builderWriter);
        System.out.println(builderWriter.toString());
        return (builderWriter.toString());
    }

    @Override
    public String getPosReceiptString(ClassSettlement classSettlement) {
        log.info("getPosReceiptString:{}", classSettlement);
        BGResult resultData = restTemplate.postForObject(bgBaseUrl + "/station/classSettlement/anony/getClassSettlementPrintInfo", classSettlement, BGResult.class);
        log.info("getPosReceiptString.resultData：{}", JSON.toJSONString(resultData));
        if (null == resultData || resultData.getCode() != BGResult.SUCCESS_CODE) {
            throw new CustomException("获取打印配置失败，" + resultData.getMsg());
        }
        Map<String, Object> printInfo = (Map<String, Object>) resultData.getData();
        if (null == printInfo) {
            return "";
        }
        printInfo.put("extraPrint", classSettlement.isExtraPrint());
        StringBuilderWriter builderWriter = new StringBuilderWriter();
        receiptSectionService.mergeTemplate(Long.valueOf(printInfo.get("enterpriseId").toString()), ReceiptType.CLASS_SETTLEMENT, PrintEnum.getByCode(PrintEnum.POS.getCode().toString()), printInfo, builderWriter);
        log.info("getClassSettlementReceiptString.builderWriter:{}", builderWriter.toString());
        return builderWriter.toString();
    }

    /**
     * 之前打印订单小票方法
     *
     * @param payOrder
     */
    @Async
    @Override
    public void feiePush(PayOrder payOrder) { //
        try {
            log.info("payOrder==={}", payOrder);
            StationDeviceManager stationDeviceManager = new StationDeviceManager();
            stationDeviceManager.setStationId(payOrder.getStationId());
            stationDeviceManager.setDeviceType("3");
            if (payOrder != null && payOrder.getOilPersonnelId() != null && !"".equals(payOrder.getOilPersonnelId())) {
                stationDeviceManager.setUserIds(payOrder.getOilPersonnelId());
            }
//            if(StringUtils.isNotEmpty(payOrder.getOilGun())){
//                stationDeviceManager.setGunNo(payOrder.getOilGun());
//            }
            List<StationDeviceManager> stationDeviceManagers = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
            //云喇叭
            stationDeviceManager.setDeviceType("4");
            List<StationDeviceManager> stationDeviceManagers1 = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
            stationDeviceManagers.addAll(stationDeviceManagers1);
            //K4小票机
            stationDeviceManager.setDeviceType("5");
            List<StationDeviceManager> stationDeviceManagers2 = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
            stationDeviceManagers.addAll(stationDeviceManagers2);

            //大喇叭机
            stationDeviceManager.setDeviceType("8");
            List<StationDeviceManager> stationDeviceManagers3 = posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
            stationDeviceManagers.addAll(stationDeviceManagers3);
            if (stationDeviceManagers == null || stationDeviceManagers.size() <= 0) {
                return;
            }

            //StringBuilder content = new StringBuilder();
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            boolean guKeFlag = true;
            boolean shangHuflag = true;
            if ("1".equals(stationDeviceManagers.get(0).getPrintType())) {
                shangHuflag = false;
            }
            if ("2".equals(stationDeviceManagers.get(0).getPrintType())) {
                guKeFlag = false;
            }

            StationDeviceManager stationDeviceManagerRes;
            List<StationDeviceManager> manageWithUser = new ArrayList<>();
            try {
                //筛选绑定了用户的小票机

                if (payOrder != null) {
                    manageWithUser = stationDeviceManagers.stream().filter(device -> {
//                        if(StringUtils.isNotBlank(device.getUserIds())){
//                            List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
//                            return userIdsList.contains(payOrder.getOilPersonnelId());
//                        }
//                        if(StringUtils.isNotEmpty(device.getGunNo())){
//                            return true;
//                        }
                        if (StationDeviceManager.bindingType_staff.equals(device.getBindingType())) {
                            //当设备选择绑定员工，但未选择指定员工时，设备需播报或打印该设备所绑定的油站的所有订单
                            if (StringUtils.isBlank(device.getUserIds())) {
                                return true;
                            } else {
                                //当设备选择绑定员工且选择了指定的员工时，设备仅播报或打印所绑定员工的订单
                                List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
                                return userIdsList.contains(payOrder.getOilPersonnelId());
                            }
                        } else if (StationDeviceManager.bindingType_gun.equals(device.getBindingType())) {
                            //当设备选择绑定油枪时，但未选择指定油枪时，设备需播报或打印该设备所绑定的油站的所有订单
                            if (StringUtils.isBlank(device.getGunNo())) {
                                return true;
                            } else {
                                //当设备选择绑定油枪时且选择了指定油枪时，设备仅播报或打印所绑定油枪的订单
                                List<String> gunNoList = Arrays.asList(device.getGunNo().split(","));
                                return gunNoList.contains(payOrder.getOilGun());
                            }
                        }
                        return false;
                    }).collect(Collectors.toList());
                }
                List<StationDeviceManager> collect = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(manageWithUser)) {
                    collect = manageWithUser.stream().filter(m -> "3".equals(m.getDeviceType()) || "5".equals(m.getDeviceType())).collect(Collectors.toList());
                }
                stationDeviceManagerRes = CollectionUtil.isNotEmpty(collect) ? collect.get(0) : null /*stationDeviceManagers.get(0)*/;
                log.info("筛选绑定用户的小票机信息：{}", stationDeviceManagerRes);
            } catch (Exception e) {
                stationDeviceManagerRes = stationDeviceManagers.get(0);
                log.error(e.getMessage());
            }
            PrintEnum printEnum = null;
            String audio = "";
            if (stationDeviceManagerRes != null) {
                audio = stationDeviceManagerRes.getAudio();
                log.info("自定义语音audio:{}", audio);

                log.info("最终小票机信息：{}", stationDeviceManagerRes);
                String deviceFactory = stationDeviceManagerRes.getDeviceFactory();

                if (StringUtils.isNotEmpty(deviceFactory)) {
                    printEnum = PrintEnum.getByCode(deviceFactory);
                }
            }
            Date now = new Date();
            if (Objects.nonNull(printEnum)) {

                StringBuilder content = new StringBuilder();
                StringBuilderWriter builderWriter = new StringBuilderWriter(content);

                if (guKeFlag || shangHuflag) {
                    int integral = StringUtils.isNumeric(payOrder.getIntegral()) ? Integer.parseInt(payOrder.getIntegral()) : 0;
                    if (integral <= 0) {
                        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                        customerPointsRecord.setOrderNo(payOrder.getOrderNo());
                        CustomerPointsRecord customerPointsRecordRes = customerPointsRecordService.getOne(customerPointsRecord);
                        log.info("订单号【{}】， 积分查询结果 : 【{}】", payOrder.getOrderNo(), customerPointsRecordRes);
                        if (Objects.nonNull(customerPointsRecordRes)) {
                            payOrder.setIntegral(MathUtil.add(null, customerPointsRecordRes.getIntegral()).toString());
                        }
                    }
                    BigDecimal presentAmt = payOrder.getPresentAmt();
                    if (presentAmt == null || presentAmt.compareTo(BigDecimal.ZERO) <= 0) {
                        PresentAmountRecord presentAmountRecord = new PresentAmountRecord();
                        presentAmountRecord.setOrderNo(payOrder.getOrderNo());
                        List<PresentAmountRecord> presentAmountRecords = presentAmountRecordMapper.query(presentAmountRecord);
                        BigDecimal presentAmount = CollectionUtil.isEmpty(presentAmountRecords) ? BigDecimal.ZERO : presentAmountRecords.get(0).getPresentAmount();
                        payOrder.setPresentAmt(presentAmount);
                    }
                    writeOrderReceiptString(payOrder, now, printEnum, stationDeviceManagers.get(0).getPrintType(), false, builderWriter);
                }
//            content.append("<BR>");
//            content.append("<BR>");

//                System.out.println(content.toString());

                switch (printEnum) {
                    case YILIANYUNK4:
                        Integer isPrintK4 = stationDeviceManagerRes.getIsPrint();
                        HashMap<String, String> k4AudioMap = new HashMap<>();
                        boolean hasPhoneK4 = StringUtils.isNotBlank(payOrder.getMobilePhone());

                        StringBuffer sbVoice = new StringBuffer();
                        try {
                            String[] split = audio.split(";");

                            //加油语音
                            String oilOrderAudio = split[0];
                            List<String> oilOrderAudioList = Arrays.asList(oilOrderAudio.split(","));
                            log.info("语音内容{}", oilOrderAudioList);
                            if (CollectionUtil.isNotEmpty(oilOrderAudioList)) {
                                for (String audioContent : oilOrderAudioList) {

                                    if ("手机尾号".equals(audioContent)) {
                                        log.info("手机尾号{}", payOrder.getMobilePhone());
                                        if (StringUtils.isNotBlank(payOrder.getMobilePhone())) {
                                            String mobilePhone = payOrder.getMobilePhone().substring(7, 11);
                                            log.info("mobilePhone{}", mobilePhone);
                                            char[] chars = mobilePhone.toCharArray();
                                            log.info("chars{}", chars);
                                            sbVoice.append("<VN>").append(1).append("</VN>");
                                            for (char aChar : chars) {
                                                sbVoice.append("<VD>").append(aChar).append("</VD>");
                                            }
                                        }

                                    } else if ("加油金额".equals(audioContent)) {
                                        sbVoice.append("<VN>").append(2).append("</VN>")
                                                .append("<VD>").append(BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString()).append("</VD>").append("<VN>0</VN>");
                                    } else if ("支付金额".equals(audioContent)) {
                                        sbVoice.append("<VN>").append(3).append("</VN>")
                                                .append("<VD>").append(BigDecimal.valueOf(payOrder.getAmt()).stripTrailingZeros().toPlainString()).append("</VD>").append("<VN>0</VN>");
                                    } else if ("枪号".equals(audioContent)) {
                                        sbVoice.append("<VN>").append(4).append("</VN>")
                                                .append("<VD>").append(payOrder.getOilGun()).append("</VD>");
                                    } else if ("油品".equals(audioContent)) {
                                        if (payOrder.getOilName() != null && payOrder.getOilName().contains("-")) {
                                            sbVoice.append("<VN>").append(9).append("</VN>")
                                                    .append("<VD>").append(payOrder.getOilName().replace("-", "")).append("</VD>");
                                        } else {
                                            sbVoice.append("<VN>").append(5).append("</VN>")
                                                    .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                                        }
                                    }

                                }
                            } else {
                                sbVoice.append("<VN>1</VN>");
                                if (StringUtils.isNotBlank(payOrder.getMobilePhone())) {
                                    String mobilePhone = payOrder.getMobilePhone().substring(7, 11);
                                    log.info("mobilePhone{}", mobilePhone);
                                    char[] chars = mobilePhone.toCharArray();
                                    log.info("chars{}", chars);
                                    sbVoice.append("<VN>").append(1).append("</VN>");
                                    for (char aChar : chars) {
                                        sbVoice.append("<VD>").append(aChar).append("</VD>");
                                    }
                                }
                                sbVoice = sbVoice.append("<VN>1</VN>").append("<VD>").append(BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString()).append("</VD>")
                                        .append("<VN>4</VN>").append("<VD>").append(payOrder.getOilGun()).append("</VD>");
                                if (payOrder.getOilName() != null && payOrder.getOilName().contains("-")) {
                                    sbVoice = sbVoice.append("<VN>").append(9).append("</VN>")
                                            .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                                } else {
                                    sbVoice = sbVoice.append("<VN>").append(5).append("</VN>")
                                            .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                                }
                            }

                            log.info("K4播报语音：{}", sbVoice);
                        } catch (Exception e) {
                            sbVoice = sbVoice.append("<VN>2</VN>").append("<VD>").append(BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString()).append("</VD>").append("<VN>0</VN>")
                                    .append("<VN>4</VN>").append("<VD>").append(payOrder.getOilGun()).append("</VD>");

                            // 不存在也不播报
                            if (payOrder.getOilName() != null) {
                                if (payOrder.getOilName().contains("-")) {
                                    sbVoice = sbVoice.append("<VN>").append(9).append("</VN>")
                                            .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                                } else {
                                    sbVoice = sbVoice.append("<VN>").append(5).append("</VN>")
                                            .append("<VD>").append(payOrder.getOilName()).append("</VD>");
                                }
                            }
                        }

                        StringBuffer finalContentVoice;
                        if (Objects.nonNull(isPrintK4) && isPrintK4.equals(0)) {
                            finalContentVoice = sbVoice;
                        } else {
                            String ylyK4Content = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                            finalContentVoice = sbVoice.append(ylyK4Content);
                        }
                        //初始化控制器类
                        Methods mK4 = Methods.getInstance();
                        Object tokenK4 = redisCacheUtil.getCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId());

                        Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                        String printK4;
                        if (Objects.nonNull(tokenK4)) {
                            printK4 = mK4.print(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getDeviceNo(), finalContentVoice.toString(), random6K4.toString(), tokenK4.toString());
                            log.info("小票机返回值{}", printK4);
                            JSONObject jsonK4 = new JSONObject(printK4);

                            if ("0".equals(jsonK4.getString("error"))) {
                                if (isPrintK4.equals(1)) {
                                    changeOrderPrintStatus(payOrder.getOrderNo());
                                }
                                break;
                            }

                        }
                        //初始化终端信息
                        mK4.init(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getClientSecret());
                        //获取token
                        String refreshTokenK4 = mK4.getFreedomToken();
                        //存入redis
                        redisCacheUtil.setCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId(), refreshTokenK4, 30, TimeUnit.DAYS);


                        printK4 = mK4.print(stationDeviceManagerRes.getDeviceNo(), finalContentVoice.toString(), random6K4.toString());
                        log.info("小票机返回值2{}", printK4);
                        JSONObject jsonK4 = new JSONObject(printK4);
                        if ("0".equals(jsonK4.getString("error")) && isPrintK4.equals(1)) {
                            changeOrderPrintStatus(payOrder.getOrderNo());
                        }


                        break;
                    case YILIANYUN:
                        Integer isPrint = stationDeviceManagerRes.getIsPrint();
                        HashMap<String, String> audioMap = new HashMap<>();
                        String phoneTail = "";
                        boolean hasPhone = StringUtils.isNotBlank(payOrder.getCustomerPhone());
                        if (hasPhone && Validator.isMobile(payOrder.getCustomerPhone())) {
                            phoneTail = payOrder.getCustomerPhone().substring(7, 11);
                            audioMap.put("手机尾号", phoneTail);
                        }
                        audioMap.put("加油金额", BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString() + "元");
                        audioMap.put("支付金额", BigDecimal.valueOf(payOrder.getAmt()).stripTrailingZeros().toPlainString() + "元");
                        audioMap.put("枪号", payOrder.getOilGun());

                        String finalOilName = "";
                        if (StringUtils.isNotEmpty(payOrder.getOilName())) {
                            finalOilName = payOrder.getOilName().replace("#", "号");
                        }
                        audioMap.put("油品", finalOilName);

                        StringBuffer sb = new StringBuffer();
                        try {
                            String[] split = audio.split(";");

                            //加油语音
                            String oilOrderAudio = split[0];
                            List<String> oilOrderAudioList = Arrays.asList(oilOrderAudio.split(","));
                            sb.append("<audio>");
                            for (String audioContent : oilOrderAudioList) {
                                if (StringUtils.equals("手机尾号", audioContent) && !hasPhone) {
                                    continue;
                                }
                                sb.append(audioContent + audioMap.get(audioContent));
                            }
                            sb.append("</audio>");
                            log.info("播报语音：{}", sb);
                        } catch (Exception e) {
                            sb = new StringBuffer();
                            sb.append("<audio>");
                            if (hasPhone) {
                                sb.append("手机尾号").append(phoneTail);
                            }
                            sb.append("支付金额").append(BigDecimal.valueOf(payOrder.getAmt()).stripTrailingZeros().toPlainString()).append("元")
                                    .append("加油金额").append(BigDecimal.valueOf(payOrder.getReceivableAmt()).stripTrailingZeros().toPlainString()).append("元")
                                    .append(payOrder.getOilGun()).append("号油枪")
                                    .append(payOrder.getOilName()).append("号油,</audio>");
                        }

                        StringBuffer finalContent;
                        if (Objects.nonNull(isPrint) && isPrint.equals(0)) {
                            finalContent = sb;
                        } else {
                            String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                            finalContent = sb.append(ylyContent);
                        }
                        //初始化控制器类
                        Methods m = Methods.getInstance();
                        Object token = redisCacheUtil.getCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId());

                        Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                        String print;
                        if (Objects.nonNull(token)) {
                            print = m.print(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getDeviceNo(), finalContent.toString(), random6.toString(), token.toString());
                            log.info("小票机返回值{}", print);
                            JSONObject json = new JSONObject(print);

                            if ("0".equals(json.getString("error"))) {
                                if (isPrint.equals(1)) {
                                    changeOrderPrintStatus(payOrder.getOrderNo());
                                }
                                break;
                            }

                        }
                        //初始化终端信息
                        m.init(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getClientSecret());
                        //获取token
                        String refreshToken = m.getFreedomToken();
                        //存入redis
                        redisCacheUtil.setCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId(), refreshToken, 30, TimeUnit.DAYS);


                        print = m.print(stationDeviceManagerRes.getDeviceNo(), finalContent.toString(), random6.toString());
                        log.info("小票机返回值2{}", print);
                        JSONObject json = new JSONObject(print);
                        if ("0".equals(json.getString("error")) && isPrint.equals(1)) {
                            changeOrderPrintStatus(payOrder.getOrderNo());
                        }

                        break;
                    case FEIE:
                        String result = FeiEPrinterUtil.printReceipt(stationDeviceManagerRes.getDeviceNo(), content.toString());
                        JSONObject resJson = new JSONObject(result);
                        if ("ok".equals(resJson.get("msg"))) {
                            changeOrderPrintStatus(payOrder.getOrderNo());
                        }

                        break;
                    default:
                        log.info("没有配置小票机，打印失败");
                        break;
                }
            }
            //音箱云播报
            StationDeviceManager voiceDevice = null;
            StationDeviceManager voiceDevice2 = null;
            for (StationDeviceManager deviceManager : manageWithUser) {
                if ("4".equals(deviceManager.getDeviceType())) {
                    voiceDevice = deviceManager;
                }
                if ("8".equals(deviceManager.getDeviceType())) {
                    voiceDevice2 = deviceManager;
                }
            }

            if (Objects.nonNull(voiceDevice)) {

                StringBuilder voiceContent = new StringBuilder();
                String voice = voiceDevice.getAudio();
                String[] split = voice.split(";");
                if (!(split.length > 0)) {
                    String oilName = "";
                    if (StringUtils.isNotEmpty(payOrder.getOilName())) {
                        oilName = payOrder.getOilName().replace("#", "号");
                    }
                    String oilGun = "";
                    if (StringUtils.isNotEmpty(payOrder.getOilGun())) {
                        oilGun = payOrder.getOilGun();
                    }
                    Double amt = payOrder.getReceivableAmt();
                    voiceContent.append(oilName).append(oilGun).append("号枪").append(amt).append("元");
                } else {


                    //加油语音
                    String oilOrderAudio = split[0];
                    List<String> voiceList = Arrays.asList(oilOrderAudio.split(","));

                    HashMap<Object, Object> voiceMap = new HashMap<>();
                    if (StringUtils.isNotEmpty(payOrder.getOilName())) {
                        voiceMap.put("油品名称", payOrder.getOilName().replace("#", "号,"));
                    } else {
                        voiceMap.put("油品名称", "");
                    }
                    if (StringUtils.isNotEmpty(payOrder.getOilGun())) {
                        voiceMap.put("枪号", payOrder.getOilGun() + "号枪,");
                    } else {
                        voiceMap.put("枪号", "");
                    }
                    voiceMap.put("应付金额", payOrder.getReceivableAmt().toString() + "元,");
                    voiceMap.put("实付金额", payOrder.getAmt().toString() + "元,");


                    for (String audioContent : voiceList) {
                        voiceContent.append(voiceMap.get(audioContent));
                    }

                }

                log.info("云播报设备播报内容{}", voiceContent);
                List<StationDeviceManager> collect = manageWithUser.stream().filter(m -> "4".equals(m.getDeviceType())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect)) {
                    log.info("云喇叭信息{}", collect.get(0));
                    deviceService.voiceBroadcast(collect.get(0).getDeviceNo(), voiceContent.toString());
                }
            }
            if (Objects.nonNull(voiceDevice2)) {
                String voice = voiceDevice2.getAudio();

                StringBuilder voiceContent = new StringBuilder();
                List<StationDeviceManager> collect2 = manageWithUser.stream().filter(m -> "8".equals(m.getDeviceType())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect2)) {
                    log.info("吹吹大喇叭{}", collect2.get(0));
                    Random random = new Random();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

/*                    String voiceBroadcastLoudspeaker( String msgId,String sn,String transactionId,String content,String totalFee,String payType,String discountFee,String attach
                            ,String lang,String nonce,String timestamp
    ) ;*/
                    String oilName = "";
                    if (StringUtils.isNotEmpty(payOrder.getOilName())) {
                        oilName = payOrder.getOilName().replace("#", "号");
                    }
                    String oilGun = "";
                    if (StringUtils.isNotEmpty(payOrder.getOilGun())) {
                        oilGun = payOrder.getOilGun();
                    }
                    Double amt = payOrder.getReceivableAmt();
                    voiceContent.append(oilName).append("号").append(oilGun).append("号枪").append(amt).append("元");

                    if (StringUtils.isNotEmpty(voice)) {
                        String s = voice.split(";")[0];
                        if (StringUtils.isNotEmpty(s)) {
                            String[] voiceList = s.split(",");
                            HashMap<Object, Object> voiceMap = new HashMap<>();
                            if (StringUtils.isNotEmpty(payOrder.getOilName())) {
                                voiceMap.put("油品名称", payOrder.getOilName().replace("#", "").replace("国标", "").replace("号", "") + "号,");
                            } else {
                                voiceMap.put("油品名称", "");
                            }
                            if (StringUtils.isNotEmpty(payOrder.getOilGun())) {
                                voiceMap.put("枪号", payOrder.getOilGun() + "号枪,");
                            } else {
                                voiceMap.put("枪号", "");
                            }
                            voiceMap.put("应付金额", payOrder.getReceivableAmt().toString() + "元,");
                            voiceMap.put("实付金额", payOrder.getAmt().toString() + "元,");
                            voiceContent = new StringBuilder();
                            for (String audioContent : voiceList) {
                                voiceContent.append(voiceMap.get(audioContent));
                            }
                        }

                    }

                    deviceService.voiceBroadcastLoudspeaker(payOrder.getOrderNo(), collect2.get(0).getDeviceNo(),
                            payOrder.getOrderNo(), voiceContent.toString(), payOrder.getReceivableAmt().toString(), "02",
                            payOrder.getDiscountAmt().toString(), null, null, random.nextInt(10) + "", simpleDateFormat.format(now));
                }
            }
        }
//        catch (EndingException e)
//        {
//            logger.info(e.getMessage());
//
//        }
        catch (Exception e) {
            logger.error(">pushConsumeToUser", e);
        }

    }

    @Override
    public String getPosOrderReceiptString(String orderNo, String deviceNo, boolean extraPrint) {
        PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(orderNo);
        if (payOrder == null) {
            payOrder = payOrderHistoryMapper.selectOrderInfoByOrdNo(orderNo);
        }
        if (payOrder == null) {
            throw new CustomException("订单不存在！");
        }
        if (Objects.isNull(payOrder.getIntegral())) {
            payOrder.setIntegral("0");
        }
        StationDeviceManager stationDeviceManage = new StationDeviceManager();
        stationDeviceManage.setStationId(payOrder.getStationId());
        stationDeviceManage.setDeviceNo(deviceNo);
        StationDeviceManager stationDeviceManagerNoCache = posMachineService.getStationDeviceManagerNoCache(stationDeviceManage);
        log.info("stationDeviceManagerNoCache:{}", stationDeviceManagerNoCache);
        if (null == stationDeviceManagerNoCache) {
            throw new CustomException("当前站点该设备不存在！");
        }
        // 没有配置则默认顾客联
        String printType = StringUtils.isBlank(stationDeviceManagerNoCache.getPrintType()) ? "1" : stationDeviceManagerNoCache.getPrintType();
        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
        customerPointsRecord.setOrderNo(payOrder.getOrderNo());
        CustomerPointsRecord customerPointsRecordRes = customerPointsRecordService.getOne(customerPointsRecord);
        log.info("订单号【{}】， 积分查询结果 : 【{}】", payOrder.getOrderNo(), customerPointsRecordRes);
        if (Objects.nonNull(customerPointsRecordRes)) {
            payOrder.setIntegral(MathUtil.add(null, customerPointsRecordRes.getIntegral()).toString());
        }
        StringBuilderWriter builderWriter = new StringBuilderWriter();
        writeOrderReceiptString(payOrder, new Date(), PrintEnum.POS, printType, extraPrint, builderWriter);
        log.info(builderWriter.toString());
        return builderWriter.toString();
    }
}
